Start learning free

LESSON 232 OF 293 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Most Frequent Element in Rust: HashMap Counts and Tie-Breaking

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

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in Rust, explained

    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

    1. Create the empty map counts, a mutable HashMap<i32, i32>.
    2. Loop over &nums with the variable num, which is a reference to an integer.
    3. Known value: if contains_key(num) is true, insert *num with counts[num] + 1.
    4. New value: otherwise insert *num with 1.
    5. Start best at nums[0]. The first number is the answer until something beats it.
    6. Walk &nums again in order.
    7. Compare counts strictly: if counts[num] > counts[&best], set best = *num.
    8. 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 &nums makes num a &i32. Methods like contains_key and the indexing counts[num] want a reference, so num is passed as it is. The key stored by insert must be a plain i32, so it is written *num.
    • best is a value, not a reference. It starts as nums[0], a copy of an i32, so looking it up needs &best.
    • Indexing panics on a missing key. Every number in nums was inserted by the first loop, so counts[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. i32 is a Copy type, which is why nums[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] gives 3.
    • [5, 2, 2, 5, 9] gives 5.
    • [7] gives 7.
    • [2, 5, 5, 2] gives 2.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free