Top K Frequent Elements
Master this topic with zero to advance depth.
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.
Visual Representation
nums = [1, 1, 1, 2, 2, 3], k = 2
Frequency Map: {1: 3, 2: 2, 3: 1}
Buckets (Count -> Elements):
1: [3]
2: [2]
3: [1]
Collect from largest count: [1, 2]Examples
1 appears 3 times, 2 appears 2 times. The top 2 most frequent elements are [1, 2].
1 is the only element, so it's the most frequent.
Level I: Brute Force (Sorting Map)
Intuition
Count the frequency of each element using a Hash Map. Convert the map entries into a list and sort the list based on frequencies in descending order. Finally, extract the first k elements.
Detailed Dry Run
| Element | Frequency | Sorted Rank |
|---|---|---|
| 1 | 3 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
Level II: Better Solution (Min-Heap)
Intuition
Maintain a Min-Heap of size k. If we find an element with a higher frequency than the heap's smallest (root), we replace it. This ensures that after processing all elements, the heap contains the k most frequent ones.
Detailed Dry Run
Heap Evolution (k=2)
| Step | Element (Freq) | Heap State | Action |
|---|---|---|---|
| 1 | 1 (3) | [(1,3)] | Push |
| 2 | 2 (2) | [(2,2), (1,3)] | Push |
| 3 | 3 (1) | [(3,1), (1,3), (2,2)] | Push & Pop Root (3,1) |
Level III: Optimal Solution (Bucket Sort)
Intuition
Frequencies range from 0 to N (length of array). We can create an array of buckets where buckets[i] contains all numbers that appear i times. By iterating through buckets from N down to 0, we can collect the top k elements in linear time.
Detailed Dry Run
Bucket Sort Visual
nums = [1,1,1,2,2,3], k = 2
Freq Map: {1:3, 2:2, 3:1}
| Freq (Bucket Index) | Numbers |
|---|---|
| 3 | [1] |
| 2 | [2] |
| 1 | [3] |
Collection (Right to Left):
- Freq 3: Add
1->res = [1] - Freq 2: Add
2->res = [1, 2] len(res) == k, STOP.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.