Series: #groupelements – seperate a list into several groups Posted on August 5, 2019July 26, 2020 by braindenny Seperate a list into several groups CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Questions Name Example When to collect result? Common error: Avoid missing the last group? Corner case: What about no groups? What about one group? Implementation: one for loop vs two for loop Code Skeleton // https://code.dennyzhang.com/summary-ranges // Basic Ideas: twopointer + simulation // // Complexity: Time O(n), Space O(1) func summaryRanges(nums []int) []string { res := []string{} // nums[i...j] i := 0 for j:=0; j<len(nums); j++ { if j+1<len(nums) && nums[j]+1 == nums[j+1] { continue } // last group or group ends if i==j { res = append(res, fmt.Sprintf("%d", nums[i])) } else { res = append(res, fmt.Sprintf("%d->%d", nums[i], nums[j])) } // need to start a new group i = j+1 } return res } See all series problems: #groupelements LeetCode: Summary Ranges See more blog posts. Post Views: 0