Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

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.

linkedin
github
slack

Post Views: 0
Posted in SeriesTagged series

Post navigation

LeetCode: Brace Expansion II
Series: #nextpermutation – Get the next permutation of an array

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.