DSA Visualizer · 25 visualizationsTop K Frequent Elements
Top K Frequent Elements
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Count how often each value appears. Start with an empty count.
Problem
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Examples
1 appears 3 times, 2 appears 2 times
Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
- k is in the range [1, number of unique elements]
Intuition
The answer only depends on how often each value shows up, not on position. Count every value once with a hash map, then the k most frequent values are just the top k entries of that count — sort the (at most n) distinct values by count and take the first k.
Brute force → Optimal
For each distinct value, scan the whole array again to count how many times it appears, then sort.
One pass to build a value → count map (O(n)), then sort the distinct entries by count and take the first k.
Complexity
Edge cases
- k equals the number of distinct values: every distinct value is returned.
- All values identical: one distinct value, always the answer when k = 1.
Common mistakes
- Sorting the original array instead of the (value, count) pairs, which loses the frequency information.
- Assuming the output order matters — the problem accepts any order, so don't over-engineer tie-breaking.