Problem overview
The method mostFrequent receives a list of integers, nums, and returns the value that appears the most times. If several values tie for the most appearances, it returns the one that shows up first in the list. The list always 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: two passes
The work splits into two simple loops.
- Count. Walk
numsonce and build a dictionary that maps each value to how many times it appears. - Choose. Walk
numsa second time, keeping the best value found so far. A value replaces it only when its count is strictly greater.
The second pass walks the list, not the dictionary, and that is what settles ties. The list meets values in the order they first appear. A later value with an equal count can't replace the current best, because the comparison is strict, so among tied values the earliest one stays.
A simpler-looking idea is to call nums.count(num) for every number. It works, but each count call scans the whole list, so the total work grows with the square of the list's length. The dictionary reads each number once per loop, which is why counting first scales much better on long lists.
Step by step
- Create an empty dictionary named
counts. Each value will be a key, and the number of its appearances the value. - Loop over
numswithfor num in nums. - Raise a known count. If
num in counts, runcounts[num] += 1. - Start a new value at 1 in the
elsebranch. A missing key can't be incremented, since reading it raisesKeyError. - Start
bestatnums[0]. The first number is the answer until a value with a higher count appears. - Walk
numsagain with a secondfor num in numsloop. - Compare counts: if
counts[num] > counts[best], makenumthe newbest. - Return
bestafter the loop.
A tie, traced
For [5, 2, 2, 5, 9] the first loop builds {5: 2, 2: 2, 9: 1}. The second loop starts with best = 5 and compares each number's count with the count of best, which is 2 throughout. The comparisons give False for 5, 2, 2, 5 and 9, because 2 is not greater than 2, and 1 is not greater than 2. So best never changes and the function returns 5, the value that appeared first.
The counts for the first example
After the first loop, counts for [1, 3, 2, 3, 1, 3] is {1: 2, 3: 3, 2: 1}. The second loop starts with best = 1, whose count is 2. The first 3 has a count of 3, which is greater, so best becomes 3. No other value reaches 3 appearances or more, so 3 is returned.
The solution in Python
class Solution:
def mostFrequent(self, nums: List[int]) -> int:
counts = {}
for num in nums:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
best = nums[0]
for num in nums:
if counts[num] > counts[best]:
best = num
return best
Some details of the code:
bestholds a value, not a count. The count is looked up withcounts[best]each time. Keeping the value is what lets the function return it at the end.- Every lookup is safe. Both
counts[num]andcounts[best]read keys that the first loop created, so noKeyErrorcan happen in the second loop. - Repeated values are compared repeatedly. A value that appears several times is checked several times in the second loop. The result stays correct, because a repeat can't beat itself under a strict
>. - Only the first loop needs a branch. Counting is the part where a key may be missing. The second loop only reads keys that exist, so it needs no
incheck. - Integer keys work like string keys. Numbers are hashable, so the same counting pattern works for letters, words or numbers.
Edge cases and common mistakes
- Using
>=in the second loop. On a tie, a later value would take over from an earlier one. For[5, 5, 2, 2], 5 and 2 both appear twice and the answer should be 5, but with>=the function returns 2. - Looping over
countsinstead ofnums. A dictionary remembers the order in which its keys were first added, so this can work. The walk overnumsstates the tie rule directly and doesn't depend on that detail. - Returning a count. The function returns the value itself, not how many times it appears. For
[4, 4, 8, 8, 8, 4]the answer is 4, which appears three times, so a function that returned the count would give 3. - A single number.
[7]never enters theifin the second loop, andbestkeeps its starting value.
Testing
[1, 3, 2, 3, 1, 3]gives3.[5, 2, 2, 5, 9]gives5.[7]gives7.[4, 4, 8, 8, 8, 4]gives4, since 4 and 8 both appear three times and 4 comes first.
