Highest Occurring Element in an Array
Pattern: Hashing basics
Count every value once in a hash map, then pick the value with the highest count, breaking ties towards the smaller value.
The problem
You are given an array nums of between 1 and 100,000 whole numbers, each fitting in 32 bits. Return the value that
appears the most times. If several values share the highest count, return the smallest of them. For example, in
[1, 2, 2, 3, 3, 3] the answer is 3, and in [4, 4, 1, 1, 3] it is 1 (4 and 1 both appear twice, and 1 is smaller).
On the original site the problem is written a little differently, so use the link above for its exact wording and its
tie rule. The function name mostFrequentElement, the limits and the "smallest on a tie" rule are this guide's own.
Think first
- How would you find the count of one value? How long would that take for every value?
- What could you store in one pass so that every count is ready afterwards?
- In the second pass, what two things must you remember, and how does the tie rule change the comparison?
Hints
Brute force, and why it fails
For each element, count how many times it appears by scanning the whole array, and keep the best. That is correct, but for 100,000 numbers it is 10 billion comparisons. Sorting first and counting runs of equal values is a fair middle ground at O(n log n). A hash map does it in O(n).
The key insight
Separate counting from deciding. One pass builds every count; a second pass over the counts picks the winner, with the tie rule written into the comparison because a hash map has no fixed order.
Dry run
| count | {} |
|---|
nums = [4, 4, 1, 1, 3]. First pass, count each value. The map starts empty.
The plan
count = empty map
for x in nums:
count[x] = count[x] + 1 # missing values start at 0
best = 0
bestCount = 0
for each (value, times) in count:
if times > bestCount or (times == bestCount and value < best):
best = value
bestCount = times
return best
Complexity
- Time
O(n)- Space
O(k)
One pass to count and one pass over the k distinct values, with average O(1) map operations. The map holds k entries,
at most n.
Edge cases
- One element: it is the answer.
- All values distinct: every count is 1, so the smallest value wins.
- Negative and very large values work, because the map does not care about the range.
- Ties:
[4, 4, 1, 1]returns 1.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int mostFrequentElement(int[] nums) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : nums) {
count.put(x, count.getOrDefault(x, 0) + 1);
}
int best = 0;
int bestCount = 0;
for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
int value = entry.getKey();
int times = entry.getValue();
if (times > bestCount || (times == bestCount && value < best)) {
best = value;
bestCount = times;
}
}
return best;
}
}C++
class Solution {
public:
int mostFrequentElement(vector<int>& nums) {
unordered_map<int, int> count;
for (int x : nums) {
count[x]++;
}
int best = 0;
int bestCount = 0;
for (auto& entry : count) {
int value = entry.first;
int times = entry.second;
if (times > bestCount || (times == bestCount && value < best)) {
best = value;
bestCount = times;
}
}
return best;
}
};Python
class Solution:
def mostFrequentElement(self, nums):
count = {}
for x in nums:
count[x] = count.get(x, 0) + 1
best = 0
best_count = 0
for value, times in count.items():
if times > best_count or (times == best_count and value < best):
best = value
best_count = times
return bestCommon mistakes
- Relying on the map's iteration order for ties, which differs between languages and runs.
- Using an array of size "largest value", which breaks on negatives and is huge for values near 10⁹.
- Comparing
times >= bestCountwithout checking the value, which returns whichever tied value came last.