Most Frequent Element
Medium · rating 1200 · hashing, arrays
The first line contains n. The second line contains n integers. Print the value that appears most often; if several tie, print the smallest of them.
Editorial
Most Frequent Element asks for the value that appears most often, breaking ties by the smallest value — a direct application of hash-map frequency counting.
Approach
Count occurrences in one pass, then scan the counts for the maximum, preferring the smaller value on a tie.
from collections import Counter
counts = Counter(nums)
best, best_count = None, -1
for v in sorted(counts):
if counts[v] > best_count:
best, best_count = v, counts[v]
return bestComplexity
Time: O(n). Space: O(k) for k distinct values.