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
- Create
counts. An emptyunordered_map<int, int>: each value will be a key and its count the value. - Loop over
nums. Every number adds one to its own count. - Known value. If
counts.count(num) > 0, add 1 tocounts[num]. - New value. Otherwise set
counts[num]to 1. - Start the winner.
int best = nums[0];makes the first number the answer until something beats it. - Walk
numsagain, in order. This second loop visits the numbers in the order they appear. - Compare counts. If
counts[num] > counts[best],numbecomes the newbest. The strict>keeps the earlier value on a tie. - 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 ofnumswas 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.numsis 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 replacesbest. - 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
numsis 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.
