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 nums. The array has at least one number.
For [1, 3, 2, 3, 1, 3] the answer is 3: it appears three times, 1 twice and 2 once. For [5, 2, 2, 5, 9], both 5 and 2 appear twice, and 5 comes first, so the answer is 5. For [7] the answer is 7.
Approach
The solution uses two passes over nums.
- Count. Build an object that maps each value to how often it appears.
- Pick. Walk the array again and keep the value with the highest count.
The second pass walks nums, not the counts object, and that is what settles ties. nums is visited in its own order, so values are met in the order they first appear. A value replaces the current best only when its count is strictly greater, so among values with the same count, the one met first stays.
On [1, 3, 2, 3, 1, 3], the first pass produces {"1": 2, "2": 1, "3": 3}. The second pass starts with best = 1, whose count is 2. The number 3 has a count of 3, which is greater, so it becomes the best. Nothing after that beats a count of 3, so the method returns 3.
On [5, 2, 2, 5, 9] the counts are {"2": 2, "5": 2, "9": 1}. The best starts at 5, with a count of 2. The number 2 also has 2, which is not greater, so 5 stays. The number 9 has 1. The answer is 5, the value that appears first in the array, even though the counts object lists 2 before 5.
That last detail is the reason for the second pass over nums. The counts say how often each value appears. Only the array knows which value came first.
A brute-force alternative counts each value by scanning the whole array for it, which takes O(n²) time. The dictionary replaces those repeated scans with one pass that remembers every count, so the later comparisons are lookups instead of searches.
Step by step
- Create the dictionary.
countsis an empty object of the type{ [key: number]: number }. - Loop over
nums. Each number adds 1 to its own count. - Known number. If
num in counts, add 1 tocounts[num]. - New number. Otherwise set
counts[num]to 1, since an unknown key reads asundefinedandundefined + 1isNaN. - Start the best at the first number.
let best: number = nums[0]is the answer until something beats it. - Walk
numsagain with a secondfor...ofloop. - Compare counts. If
counts[num] > counts[best], makenumthe newbest. The comparison is strict, so on a tiebestkeeps the earlier value. - Return
best.
The solution in TypeScript
class Solution {
mostFrequent(nums: number[]): number {
const counts: { [key: number]: number } = {};
for (let num of nums) {
if (num in counts) {
counts[num] += 1;
} else {
counts[num] = 1;
}
}
let best: number = nums[0];
for (let num of nums) {
if (counts[num] > counts[best]) {
best = num;
}
}
return best;
}
}
Details worth knowing:
- Number keys become strings. The type
{ [key: number]: number }is allowed, but at run time an object's keys are always strings.counts[3]andcounts["3"]are the same entry. Reading with a number works because the number is converted to a string for the lookup. Object keys that look like whole numbers are also listed in ascending numeric order: keys added as 10, 2 and 1 come out as["1", "2", "10"]. The code never relies on that order. - The
inoperator asks whether the key exists, even when its value is 0 or another falsy value. Here every stored count is at least 1. - Negative numbers work.
[-1, 4, 4, -1, 4]returns 4. A key such as"-1"is a perfectly good string. - Comparing with
best. The first round comparesnums[0]with itself, which is false, so it changes nothing.
Complexity
Time: O(n). Each of the two loops visits every number once, and each object lookup or update takes constant time on average.
Space: O(k), where k is the number of different values, because counts has one entry per distinct value. In the worst case k equals n.
Edge cases and common mistakes
- Walking
countsto find the best. The keys come out as strings, in an order that doesn't follow the array, so the tie rule would break and you would have to convert them back to numbers. - Using
>=. The last tied value would win. For[5, 2, 2, 5, 9]it would return 2. - Forgetting the first-time case. The counts would be
NaN, and comparisons withNaNare always false, sobestwould never change. - One element.
[7]returns 7: the counts object is{"7": 1}andbestnever changes. - All values different. Every count is 1, no count is strictly greater than another, and the method returns
nums[0], the first value.
Testing
[1, 3, 2, 3, 1, 3]gives3.[5, 2, 2, 5, 9]gives5.[7]gives7.[-1, 4, 4, -1, 4]gives4.
