Problem overview
The method mostFrequent receives an array of integers, nums, and returns the value that appears the most times. If several values tie, it returns the one that shows up first in the array. The array always has at least one number.
In [1, 3, 2, 3, 1, 3] the value 3 appears three times, 1 twice and 2 once, so the answer is 3. In [5, 2, 2, 5, 9], 5 and 2 both appear twice. The 5 is at index 0 and the 2 first shows up at index 1, so the answer is 5. For [7] the answer is 7.
Approach: count first, then pick
Finding the winner needs the count of every value, so the work has two passes.
The first pass fills a map from value to count, the same counting pattern used for letters and words. The second pass walks nums again, keeping the best value so far and replacing it only when a value has a strictly higher count. The tie rule comes from this second pass: it walks the array, not the map, so values are met in the order of their first appearance (and a repeated value is simply compared again, with the same result). Because a tie doesn't replace the best, the earlier value stays.
Walking the map instead would be a trap. A HashMap gives its entries in an order that has nothing to do with the array, so you couldn't tell which of two tied values came first.
Step by step
- Create the count map.
HashMap<Integer, Integer> countsstarts empty. Keys and values areInteger, the object version ofint, and Java converts automatically. - Loop over
numswithfor (int num : nums). - Known value: if
counts.containsKey(num), put it again withcounts.get(num) + 1. - New value: in the
else, put it with 1.getwould returnnullfor a missing key, and adding tonullcrashes. - Start the best value as
int best = nums[0];, the first number, which is the answer until something beats it. - Walk
numsagain in order, with a second loop. - Compare counts: if
counts.get(num) > counts.get(best), thenbest = num. The comparison is strict, so a tie keeps the earlier value. - Return
best.
The solution in Java
class Solution {
public int mostFrequent(int[] nums) {
HashMap<Integer, Integer> counts = new HashMap<>();
for (int num : nums) {
if (counts.containsKey(num)) {
counts.put(num, counts.get(num) + 1);
} else {
counts.put(num, 1);
}
}
int best = nums[0];
for (int num : nums) {
if (counts.get(num) > counts.get(best)) {
best = num;
}
}
return best;
}
}
Java details worth knowing:
- Comparing
Integervalues with>is fine. Relational operators unbox the numbers. With==it would be different: twoIntegerobjects holding 1000 are not==, because that compares references.(Integer) 1000 == (Integer) 1000isfalse, whileequalsgivestrue. That is why the lesson compares with>and never with==on the counts. - Autoboxing in
counts.get(num). The argumentnumis anint, which Java boxes to anIntegerto look it up, and the result is unboxed for the comparison. The key exists for everynum, because the first pass added all of them. - Two readings of the same array. The second loop uses the same variable name
num. That is legal, because the first loop's variable is out of scope after its closing brace.
Tracing the two examples
For [5, 2, 2, 5, 9] the first pass builds {2=2, 5=2, 9=1}. The second pass starts with best = 5 and then shows the value of best after each element:
5 -> best 5
2 -> best 5
2 -> best 5
5 -> best 5
9 -> best 5
The 2 has the same count as 5, which isn't strictly greater, so 5 stays. For [1, 3, 2, 3, 1, 3] the map is {1=2, 2=1, 3=3} and the second pass goes like this:
1 -> best 1
3 -> best 3
2 -> best 3
3 -> best 3
1 -> best 3
3 -> best 3
The value 1 starts as best, since it is nums[0]. At the second element the 3, with count 3, beats 1, with count 2, and nothing beats it afterwards.
Complexity
Time: O(n) for n numbers. Each of the two passes does a constant amount of map work per element on average.
Space: O(k), where k is the number of distinct values, since the map has one entry per value.
Why two loops
Could one loop do both jobs? Not directly: when you reach a number you only know its count so far, not its final count, and a later number may overtake it. The count pass has to finish before the choice is safe. That is why the lesson separates "count everything" from "pick the winner". Both passes are linear, so two of them still cost O(n).
Edge cases and common mistakes
- Using
>=in the second loop. A later value with an equal count would replace the earlier one. For[5, 2, 2, 5, 9]the answer would become 2 instead of 5. - Looping over the map for the answer. Ties would be settled by hash order, not by position in the array.
- Returning the count. The method returns the value, not how many times it appears.
- A single element.
[7]works with no special case:beststarts as 7 and nothing beats it.
Testing
[1, 3, 2, 3, 1, 3]gives3.[5, 2, 2, 5, 9]gives5.[7]gives7.[4, 4, 9, 9, 9, 4]gives4: both appear three times, and 4 comes first.
