Problem overview
The function most_frequent receives a vector of integers, nums, and returns the value that appears the most times. If several values tie, the one that appears first in nums wins. 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], both 5 and 2 appear twice, and 5 shows up first, so the answer is 5.
Approach: count, then pick in order
The solution makes two passes. The first pass fills a map from value to count. The second pass walks nums again, from left to right, and keeps the value with the highest count seen so far.
Walking nums in the second pass, rather than looping over the map, is what settles ties. A HashMap has no meaningful order, but nums does: values are met in the order they first appear. A value replaces the best only if its count is strictly higher, so on a tie the earlier value stays.
Step by step
- Create the empty map
counts, a mutableHashMap<i32, i32>. - Loop over
&numswith the variablenum, which is a reference to an integer. - Known value: if
contains_key(num)is true, insert*numwithcounts[num] + 1. - New value: otherwise insert
*numwith 1. - Start
bestatnums[0]. The first number is the answer until something beats it. - Walk
&numsagain in order. - Compare counts strictly: if
counts[num] > counts[&best], setbest = *num. - Return
best.
The solution in Rust
impl Solution {
fn most_frequent(nums: Vec<i32>) -> i32 {
let mut counts: HashMap<i32, i32> = HashMap::new();
for num in &nums {
if counts.contains_key(num) {
counts.insert(*num, counts[num] + 1);
} else {
counts.insert(*num, 1);
}
}
let mut best = nums[0];
for num in &nums {
if counts[num] > counts[&best] {
best = *num;
}
}
return best;
}
}
The Rust details worth a closer look:
- References and dereferencing. Looping over
&numsmakesnuma&i32. Methods likecontains_keyand the indexingcounts[num]want a reference, sonumis passed as it is. The key stored byinsertmust be a plaini32, so it is written*num. bestis a value, not a reference. It starts asnums[0], a copy of ani32, so looking it up needs&best.- Indexing panics on a missing key. Every number in
numswas inserted by the first loop, socounts[num]in the second loop always finds its key.nums[0]would panic on an empty vector, which the lesson rules out. - Integers are copied.
i32is aCopytype, which is whynums[0]can be read without clone or move.
Complexity
Time: O(n). Each of the two loops visits the n numbers once, and each map operation takes constant time on average.
Space: O(k), where k is the number of different values, since the map has one entry per value. In the worst case, k equals n.
Tracing a tie
Take [5, 2, 2, 5, 9]. After the first loop the map holds 5: 2, 2: 2 and 9: 1. Now the second loop runs with best = 5. The first number, 5, has count 2, which is not greater than the count of best, itself. Next, 2 has count 2, not greater than 2, so best stays 5. The next two numbers behave the same, and 9 has count 1. The loop ends and 5 is returned.
Now take [1, 3, 2, 3, 1, 3]. The counts are 1: 2, 3: 3 and 2: 1. With best = 1, the number 1 doesn't beat itself and 3 does (3 > 2), so best becomes 3. After that nothing has a count above 3, and 3 is returned.
Why two passes
One pass could keep the best while counting, but a value's count only reaches its final size at its last appearance, which makes the tie rule harder to get right. Two simple loops, one to count and one to choose, are easier to reason about, and they still run in linear time.
Other ways to do it
Sorting the vector would put equal values side by side and allow counting runs, but it destroys the original order that the tie rule depends on, so you would have to track positions as well. Comparing every value with every other value takes O(n²). The map keeps the whole job linear and keeps the original vector untouched.
If counts could be large, i32 would be a limit: a value appearing more than 2,147,483,647 times would overflow the count. In the lessons' optimized builds the overflow wraps silently, so for such sizes a wider type like i64 or usize would be the right choice. Real inputs of this lesson are far below that.
The map also needs to hold only the values that actually occur, so memory grows with the number of different values, not with how large the values themselves are. A vector containing the numbers 1 and 1,000,000,000 needs just two entries.
Edge cases and common mistakes
- Using
>=in the second loop. The last of the tied values would win.[5, 2, 2, 5, 9]would then return 2 instead of 5. - Looping over the map for the answer. The map's order is arbitrary, so ties would be broken unpredictably.
- One element.
[7]returns 7. - Tie between a late and an early value.
[2, 5, 5, 2]returns 2, because 2 appears first.
Testing
[1, 3, 2, 3, 1, 3]gives3.[5, 2, 2, 5, 9]gives5.[7]gives7.[2, 5, 5, 2]gives2.
