Start learning free

LESSON 229 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Most Frequent Element in Go: Count, Then Pick

Practice Read the full explanation

Given an array of integers nums, return the value that appears in it the most times.

If several values tie for the most appearances, return the one that shows up first in nums. nums has at least one number.

Example 1:

Input: nums = [1, 3, 2, 3, 1, 3]
Output: 3
Explanation: 3 appears three times, 1 twice and 2 once.

Example 2:

Input: nums = [5, 2, 2, 5, 9]
Output: 5
Explanation: 5 and 2 both appear twice. 5 shows up first (at index 0, while 2 first shows up at index 1), so the answer is 5.

Example 3:

Input: nums = [7]
Output: 7
Explanation: The only value is also the most frequent one.
STEP 1 OF 8
    Ctrl + Enter to check

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in Go, explained

    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

    1. Create counts, a map[int]int{}: value to number of appearances.
    2. Loop over nums with for _, num := range nums.
    3. Known value: if _, ok := counts[num]; ok is true when the value was seen before, so add 1 to its count.
    4. New value: in the else branch, set its count to 1.
    5. Start best at nums[0]. The first number is the answer until something appears more often.
    6. Loop over nums again. Not over the map: this keeps the first-appearance order.
    7. Compare counts. If counts[num] > counts[best], make num the new best. The comparison is strict, so a value that only ties never replaces the earlier one.
    8. 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:

    numcounts[num]counts[best]counts[num] > counts[best]
    522false
    222false
    222false
    522false
    912false

    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 range visits a map. A second loop over counts would give different tie results from run to run. fmt.Println prints maps sorted by key, which can hide this in output.
    • Zero values. Reading a missing key from counts gives 0, which is why counts[num] > counts[best] is safe to write. Here every num and best is a key anyway.
    • Shorter counting. counts[num]++ replaces the whole if and else, 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] returns 7.
    • 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 best at 0. The answer can be any integer, including a negative one, so a made-up start can be wrong. Starting from nums[0] always gives a real element of the slice.

    Testing

    • [1, 3, 2, 3, 1, 3] returns 3.
    • [5, 2, 2, 5, 9] returns 5.
    • [7] returns 7.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free