Start learning free

LESSON 225 OF 667 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Most Frequent Element in C++: Counts and Tie-Breaking

Practice Read the full explanation

Given a vector 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

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in C++, explained

    Problem overview

    The function mostFrequent receives a vector<int> named nums and returns the value that appears the most times. When several values tie, the one that appears first in nums is the answer. The vector has at least one number.

    For [1, 3, 2, 3, 1, 3] the answer is 3, which appears three times. For [5, 2, 2, 5, 9] the values 5 and 2 both appear twice, and 5 comes first, so the answer is 5. For [7] the answer is 7.

    Approach: count first, then pick

    The solution makes two passes. The first pass builds a map from each value to its count. The second pass finds the winner, and it walks nums itself, not the map. That choice settles the ties: walking nums meets the values in the order they first appear, and a later value replaces the best one only when its count is strictly larger. A value with an equal count never takes over, so among tied values the earliest one stays.

    Walking the map instead would not work for ties, because an unordered_map doesn't remember the order in which keys were inserted.

    A brute-force alternative counts each number by scanning the whole vector again, which takes O(n²) time. The map replaces those repeated scans with one lookup per number, so the whole job takes two linear passes.

    Think of the second pass as a contest that runs in the order the values first show up. The current best is the champion. A challenger must have a strictly higher count to win, so a challenger that only equals the champion loses, and the earlier value keeps the title. Challengers equal to the champion's own value are harmless: the same value later in nums has the same count and doesn't beat itself.

    Step by step

    1. Create counts. An empty unordered_map<int, int>: each value will be a key and its count the value.
    2. Loop over nums. Every number adds one to its own count.
    3. Known value. If counts.count(num) > 0, add 1 to counts[num].
    4. New value. Otherwise set counts[num] to 1.
    5. Start the winner. int best = nums[0]; makes the first number the answer until something beats it.
    6. Walk nums again, in order. This second loop visits the numbers in the order they appear.
    7. Compare counts. If counts[num] > counts[best], num becomes the new best. The strict > keeps the earlier value on a tie.
    8. Return best.

    The solution in C++

    class Solution {
    public:
        int mostFrequent(vector<int>& nums) {
            unordered_map<int, int> counts;
            for (int num : nums) {
                if (counts.count(num) > 0) {
                    counts[num] += 1;
                } else {
                    counts[num] = 1;
                }
            }
            int best = nums[0];
            for (int num : nums) {
                if (counts[num] > counts[best]) {
                    best = num;
                }
            }
            return best;
        }
    };
    

    The C++ details worth knowing:

    • counts[num] in the second loop is safe. Every number of nums was counted in the first loop, so each lookup finds an existing key. The subscript would insert a 0 for a missing key, but none is missing here, so the map doesn't change.
    • nums[0] is unchecked. It is valid only because the vector is never empty. On an empty vector it would be undefined behaviour.
    • nums is passed by reference. The & avoids copying the vector, and the function doesn't modify it.
    • The map's order is unspecified. That is why the second loop goes over the vector.

    A note on the second loop

    The comparison counts[num] > counts[best] does two map lookups on every turn. That is fine for this lesson, since each lookup takes constant time on average. If you wanted to avoid the repeated lookups, you could keep the best count in its own int variable and update both together. The lesson's version keeps one variable, which is easier to follow.

    Complexity

    Time: O(n) on average. Each of the two loops visits n numbers, and every map lookup or update takes constant time on average. Space: O(k), where k is the number of different values, for the map.

    Edge cases and common mistakes

    • Ties. [5, 2, 2, 5, 9] returns 5. Using >= in the second loop would return 2, because the later tied value would replace the earlier one.
    • Walking the map to find the winner. It gives a tie answer that can change from one implementation to another.
    • One element. [7] returns 7: both loops run once and nothing replaces best.
    • Negative values. They work as keys like any other integer. For [3, 3, 4, 4, 4] the answer is 4.
    • Stopping after the first loop. The map alone can't answer the question, because it has no notion of which value came first. The second pass over nums is what applies the tie rule.
    • Returning the count. The function returns the value, not how many times it appears.

    Testing

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