Go for coding rounds
Maps, slices, heaps, runes, binary search and backtracking, with the Go traps.
Two sum with a map[int]int from value to index. What is the time and space?
All questions with explanations (answers shown)
1. Two sum with a
map[int]intfrom 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.
a := []int{1, 2, 3, 4}; b := a[1:3]; slices.Reverse(b); fmt.Println(a)prints:Answer:
[1 3 2 4]bsharesa's backing array, so reversingbswaps the middle two elements ofa. Useslices.Clonewhen you need an independent copy.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), noth.Push(x).4. Inside
for i, r := range sover a string, what areiandr?Answer:
iis the byte offset,ris a runeRanging over a string decodes UTF-8.
ijumps by the size of each character in bytes.s[i]would give a byte, not a rune.5.
i := sort.SearchInts(s, x)andxis bigger than every element. What must you do before readings[i]?Answer: Check
i < len(s), because it returnslen(s)sort.Searchand its helpers return n when the condition is never true. Readings[n]panics.6. In an LRU cache built with
container/listand 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. 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; saveslices.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.
dp := make([][]int, n)and thendp[0][0] = 1. What happens?Answer: It panics: each row is a nil slice until you
makeitmake([][]int, n)makes n nil rows. Loop andmakeeach row before you index into it.