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
- Create an empty object named
countswithconst. - Loop over
numswithfor...of, using the variablenum. - Count a repeat: if
num in counts, add 1 tocounts[num]. - Count a first sighting: in the
else, setcounts[num]to 1. - Pick a starting champion: declare
bestwithletand set it tonums[0]. It is the answer until something appears more often. - Walk
numsa second time, again in order. - Compare counts: if
counts[num] > counts[best], makenumthe newbest. - Return
bestafter 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". Readingcounts[num]converts the same way, so lookups work. ButObject.keys(counts)gives strings, such as["1", "2", "3"], not numbers. That is one more reason to returnbest, which comes fromnumsand is still a number. - Integer-like keys are sorted. For
[5, 2, 2, 5, 9], the counts object lists its keys as2,5,9, ascending, whatever the order they were added in. If the second loop walkedcounts, it would meet 2 before 5 and return 2, which is the wrong answer for this lesson. Walkingnumsavoids that. - A missing key is
undefined, andundefined + 1isNaN, 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
countsinstead ofnums. The keys come out in a different order, so ties may be settled the wrong way, and the keys are strings, not numbers. - Starting
bestat 0. The array can contain any integers, and counts[0] might not exist. Starting withnums[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]gives3.[5, 2, 2, 5, 9]gives5.[7]gives7.
