Count how many times each value appears in an int slice
Implement counts(in) returning a map[int]int from each value to the number of times it occurs. Requirement: a single pass, O(n) time. Example: counts([]int{1,2,2,3,3,3}) → {1:1, 2:2, 3:3}.
func counts(in []int) map[int]int {
// your code here
return nil
}
Write the implementation.
Make the result with make(map[int]int), then range over the slice doing m[v]++ for each value. A read of a missing key returns the zero value 0, so m[v]++ works on the first sighting without an explicit check. Each map access is O(1), so the whole count is one O(n) pass, and the map's keys double as the set of distinct values.
- ✗Guarding with
okbecause you think a missing key panics - ✗Believing a map cannot be incremented in place
- ✗Forgetting that a missing int key reads as 0
- →How do you find the most frequent value once you have the counts?
- →How would you list only the distinct values from this map?
Solution
m[v]++ relies on the zero value of a missing key — no pre-check needed.
func counts(in []int) map[int]int {
m := make(map[int]int)
for _, v := range in {
m[v]++ // a missing key reads as 0
}
return m
}
// counts([]int{1,2,2,3,3,3}) -> map[1:1 2:2 3:3]
Reading a missing key in Go returns the type's zero value (0 for int), not a panic, so m[v]++ correctly starts at 1 on the first sighting. Each access is O(1), the whole count is O(n). The keys of the resulting map are the set of distinct values.