Dev Skills
Go tests·8 questions

Go for coding rounds

Maps, slices, heaps, runes, binary search and backtracking, with the Go traps.

1 / 8

Two sum with a map[int]int from value to index. What is the time and space?

All questions with explanations (answers shown)
  1. 1. Two sum with a map[int]int from value to index. What is the time and space?

    Answer: O(n) time, O(n) space

    One pass, with an O(1) average map lookup per element, and the map can hold up to n entries.

  2. 2. a := []int{1, 2, 3, 4}; b := a[1:3]; slices.Reverse(b); fmt.Println(a) prints:

    Answer: [1 3 2 4]

    b shares a's backing array, so reversing b swaps the middle two elements of a. Use slices.Clone when you need an independent copy.

  3. 3. You need the top 10 words out of 5 million distinct words. Which is the better follow-up to sorting everything?

    Answer: A min-heap of size 10 with container/heap: O(n log k)

    Keep only k items. Each push and pop costs O(log k), so the total is O(n log k) instead of O(n log n). Remember to call heap.Push(h, x), not h.Push(x).

  4. 4. Inside for i, r := range s over a string, what are i and r?

    Answer: i is the byte offset, r is a rune

    Ranging over a string decodes UTF-8. i jumps by the size of each character in bytes. s[i] would give a byte, not a rune.

  5. 5. i := sort.SearchInts(s, x) and x is bigger than every element. What must you do before reading s[i]?

    Answer: Check i < len(s), because it returns len(s)

    sort.Search and its helpers return n when the condition is never true. Reading s[n] panics.

  6. 6. In an LRU cache built with container/list and a map, why does each list entry store its key?

    Answer: Because eviction starts from the list node, and you need the key to delete it from the map

    You evict from the back of the list. Without the key you cannot remove the map entry, and the map keeps the evicted node alive.

  7. 7. A backtracking function does out = append(out, cur) and every saved subset ends up the same. Why?

    Answer: All saved slices share cur's backing array, so later changes overwrite them; save slices.Clone(cur)

    A slice is a header pointing at an array. Saving it saves the pointer, not the values. Copy at the moment you save the answer.

  8. 8. dp := make([][]int, n) and then dp[0][0] = 1. What happens?

    Answer: It panics: each row is a nil slice until you make it

    make([][]int, n) makes n nil rows. Loop and make each row before you index into it.