Start learning free

LESSON 226 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Most Frequent Element in Java: Two Passes with a HashMap

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

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in Java, explained

    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

    1. Create the count map. HashMap<Integer, Integer> counts starts empty. Keys and values are Integer, the object version of int, and Java converts automatically.
    2. Loop over nums with for (int num : nums).
    3. Known value: if counts.containsKey(num), put it again with counts.get(num) + 1.
    4. New value: in the else, put it with 1. get would return null for a missing key, and adding to null crashes.
    5. Start the best value as int best = nums[0];, the first number, which is the answer until something beats it.
    6. Walk nums again in order, with a second loop.
    7. Compare counts: if counts.get(num) > counts.get(best), then best = num. The comparison is strict, so a tie keeps the earlier value.
    8. 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 Integer values with > is fine. Relational operators unbox the numbers. With == it would be different: two Integer objects holding 1000 are not ==, because that compares references. (Integer) 1000 == (Integer) 1000 is false, while equals gives true. That is why the lesson compares with > and never with == on the counts.
    • Autoboxing in counts.get(num). The argument num is an int, which Java boxes to an Integer to look it up, and the result is unboxed for the comparison. The key exists for every num, 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: best starts as 7 and nothing beats it.

    Testing

    • [1, 3, 2, 3, 1, 3] gives 3.
    • [5, 2, 2, 5, 9] gives 5.
    • [7] gives 7.
    • [4, 4, 9, 9, 9, 4] gives 4: both appear three times, and 4 comes first.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free