Start learning free

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

Most Frequent Element in JavaScript: Count, Then Pick the Winner

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

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in JavaScript, explained

    Problem overview

    The method mostFrequent(nums) receives a non-empty array of integers and returns the value that appears the most times. If several values tie, it returns the one that shows up first in nums.

    For [1, 3, 2, 3, 1, 3] the value 3 appears three times, 1 twice and 2 once, so the answer is 3. For [5, 2, 2, 5, 9], both 5 and 2 appear twice. The 5 sits at index 0 and the 2 first appears at index 1, so the answer is 5.

    Approach

    The problem splits into two passes. The first pass builds a counting dictionary: each number maps to how many times it appears. The second pass decides the winner, using the "best so far" pattern: keep the best candidate and replace it only when another value has a higher count.

    The tie rule is handled by what the second pass walks over. If it walked the dictionary, the order of the keys would decide ties, and that order is not the order of first appearance. By walking nums again, in its original order, the loop meets the values in the order they first show up. With a strict "greater than" test, a value that merely ties the best never replaces it, so the earliest of the tied values stays.

    Step by step

    1. Create an empty object named counts with const.
    2. Loop over nums with for...of, using the variable num.
    3. Count a repeat: if num in counts, add 1 to counts[num].
    4. Count a first sighting: in the else, set counts[num] to 1.
    5. Pick a starting champion: declare best with let and set it to nums[0]. It is the answer until something appears more often.
    6. Walk nums a second time, again in order.
    7. Compare counts: if counts[num] > counts[best], make num the new best.
    8. Return best after the second loop.

    The solution in JavaScript

    class Solution {
        mostFrequent(nums) {
            const counts = {};
            for (let num of nums) {
                if (num in counts) {
                    counts[num] += 1;
                } else {
                    counts[num] = 1;
                }
            }
            let best = nums[0];
            for (let num of nums) {
                if (counts[num] > counts[best]) {
                    best = num;
                }
            }
            return best;
        }
    }
    

    Some JavaScript details are worth a closer look:

    • Object keys are strings. When you write counts[3], the number 3 is converted to the key "3". Reading counts[num] converts the same way, so lookups work. But Object.keys(counts) gives strings, such as ["1", "2", "3"], not numbers. That is one more reason to return best, which comes from nums and is still a number.
    • Integer-like keys are sorted. For [5, 2, 2, 5, 9], the counts object lists its keys as 2, 5, 9, ascending, whatever the order they were added in. If the second loop walked counts, it would meet 2 before 5 and return 2, which is the wrong answer for this lesson. Walking nums avoids that.
    • A missing key is undefined, and undefined + 1 is NaN, so a first sighting must set the count to 1 instead of adding.

    Tracing the examples

    For [1, 3, 2, 3, 1, 3], the counting pass produces the object {1: 2, 2: 1, 3: 3}. The second pass starts with best = 1 (count 2). It sees 1 (not greater than itself), then 3 (count 3, greater than 2, so best = 3), then 2, 3, 1 and 3, none of which beats a count of 3. The function returns 3.

    For [5, 2, 2, 5, 9], the counts are {2: 2, 5: 2, 9: 1}. best starts as 5. The 2 has count 2, equal to the count of 5 and not greater, so it doesn't replace it. The 9 has count 1. The result is 5.

    A Map keeps the numbers as numbers

    A Map avoids the string-key conversion. Its keys keep their type, and it remembers insertion order. Counting [1, 3, 2, 3, 1, 3] into a Map gives Map {1 => 2, 3 => 3, 2 => 1}, in the order the numbers first appeared, and [...map.keys()] is [1, 3, 2], all numbers. With a Map, walking the keys would settle ties by first appearance too. The lesson uses a plain object, and its second pass over nums works with either.

    Complexity

    Time: O(n). Each of the two loops visits every element once, and every dictionary operation takes constant time on average.

    Space: O(k), where k is the number of distinct values, because the object holds one entry per distinct value. In the worst case, with no repeats, that is n entries.

    Edge cases and common mistakes

    • Using >= in the second loop. Each tied value would replace the previous one, and the last of the tied values would win. For [2, 5, 2, 5] that would return 5 instead of 2.
    • Walking counts instead of nums. The keys come out in a different order, so ties may be settled the wrong way, and the keys are strings, not numbers.
    • Starting best at 0. The array can contain any integers, and counts[0] might not exist. Starting with nums[0] always gives a real value.
    • A single number. [7] returns 7: both loops run once and nothing beats it.
    • Returning the count. The question asks for the value, not how often it appears.

    Testing

    • [1, 3, 2, 3, 1, 3] gives 3.
    • [5, 2, 2, 5, 9] gives 5.
    • [7] gives 7.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free