Most Common Value
Medium · rating 1250 · Arrays, Hashing
The first line contains n. The second line contains n integers. Print the value that appears most often. If several values tie for most frequent, print the smallest of them.
Constraints: 1 ≤ n ≤ 105
Editorial
Approach
Tally each value's frequency in a hash map. Find the highest frequency, then among all values sharing it, take the minimum to break ties deterministically.
from collections import Counter
c = Counter(nums)
best = max(c.values())
print(min(k for k, v in c.items() if v == best))Complexity
Time: O(n). Space: O(n).
Related problems
- Two Sum Exists — Medium
- Most Frequent Element — Medium
- Count Pairs With Difference — Medium
- Count Pairs with Sum — Medium
- Subarrays Summing to K — Hard
- Two Sum — Easy