Problem overview
The function mostFrequent takes a slice of integers, nums, and returns the value that appears the most times. If several values tie for the highest count, the one that appears first in nums wins. The slice has at least one number.
For [5, 2, 2, 5, 9], the values 5 and 2 both appear twice. The 5 shows up at index 0 and the 2 at index 1, so the answer is 5. For [1, 3, 2, 3, 1, 3] the answer is 3, which appears three times.
Approach: two passes
The first pass counts how often each value occurs, using a map from value to count. The second pass finds the value with the highest count.
It might seem natural to loop over the map in the second pass, but Go visits map entries in random order, so a tie would be settled by luck. Looping over nums again meets the values in the order they appear in the input. Combined with a strict comparison, the first value to reach the top count keeps the title, which is exactly the tie-break the problem asks for. The same value is visited more than once, but that is harmless: a repeat can never beat itself.
Counting without a map is possible: for each number, scan the whole slice and count its copies. That costs O(n²) comparisons, which grows quickly for long slices. The map turns "how many times has this value appeared?" into a single lookup.
It is also tempting to track the best value during the first pass. That works for finding the highest count, but not for the tie rule: a value that reaches the top count first is not necessarily the one that appears first in nums. In [1, 2, 2, 1] the 2 reaches a count of 2 before the 1 does, yet the 1 is the value that appears first, so the 1 is the required answer. Counting everything first and then reading nums from the left separates the two jobs cleanly.
Step by step
- Create
counts, amap[int]int{}: value to number of appearances. - Loop over
numswithfor _, num := range nums. - Known value:
if _, ok := counts[num]; okis true when the value was seen before, so add 1 to its count. - New value: in the
elsebranch, set its count to 1. - Start
bestatnums[0]. The first number is the answer until something appears more often. - Loop over
numsagain. Not over the map: this keeps the first-appearance order. - Compare counts. If
counts[num] > counts[best], makenumthe newbest. The comparison is strict, so a value that only ties never replaces the earlier one. - Return
best.
Tracing the tie
For [5, 2, 2, 5, 9], the first pass produces map[2:2 5:2 9:1]. Then best starts as 5, whose count is 2. The second pass looks at each number in order:
| num | counts[num] | counts[best] | counts[num] > counts[best] |
|---|---|---|---|
| 5 | 2 | 2 | false |
| 2 | 2 | 2 | false |
| 2 | 2 | 2 | false |
| 5 | 2 | 2 | false |
| 9 | 1 | 2 | false |
No value has a count above 2, so best stays 5. The 2 only ties with it, and a tie doesn't replace the earlier value.
With >= the tie would go to whichever tied value the loop meets last. On [5, 5, 2, 2] the strict version returns 5, while the >= version returns 2, which breaks the rule that the earlier value wins.
The solution in Go
func mostFrequent(nums []int) int {
counts := map[int]int{}
for _, num := range nums {
if _, ok := counts[num]; ok {
counts[num] += 1
} else {
counts[num] = 1
}
}
best := nums[0]
for _, num := range nums {
if counts[num] > counts[best] {
best = num
}
}
return best
}
Go details worth knowing
- Map order is random. Go deliberately randomises the order in which
rangevisits a map. A second loop overcountswould give different tie results from run to run.fmt.Printlnprints maps sorted by key, which can hide this in output. - Zero values. Reading a missing key from
countsgives 0, which is whycounts[num] > counts[best]is safe to write. Here everynumandbestis a key anyway. - Shorter counting.
counts[num]++replaces the wholeifandelse, because an absent key starts from 0.
Complexity
Both loops visit each of the n numbers once, and a map lookup or update takes constant time on average, so the time is O(n). The map holds one entry per distinct value, so the extra space is O(n) in the worst case, when every value is different.
Edge cases and common mistakes
- One element.
[7]returns7. - Ties. The answer is the value that appears first in
nums, not the smallest and not the one that reaches the top count first. - Looping over the map for the answer makes tie results random.
- Using
>=lets a later tied value replace an earlier one. - Starting
bestat 0. The answer can be any integer, including a negative one, so a made-up start can be wrong. Starting fromnums[0]always gives a real element of the slice.
Testing
[1, 3, 2, 3, 1, 3]returns3.[5, 2, 2, 5, 9]returns5.[7]returns7.
