Top K Frequent Elements
Find the k most frequent elements using sorting, a min-heap, or bucket sort.
Top K Frequent Elements
Problem: Given an array of numbers, return the k most frequently occurring elements. The answer can be in any order.
Example:
- Input:
nums = [1, 1, 1, 2, 2, 3],k = 2 - Output:
[1, 2](1 appears 3 times, 2 appears 2 times — those are the top 2)
Note
First count how many times each number appears. Then figure out which k numbers appeared the most.
Brute Force — Count + Sort
View Brute Force
Optimal — Min Heap of Size k
View Optimal Solution
Best — Bucket Sort
View Best Solution
| Approach | Time | Space | Notes |
|---|---|---|---|
| Sort by frequency | O(n log n) | O(n) | Simple, easy to write |
| Min Heap of size k | O(n log k) | O(n) | Better when k is small |
| Bucket Sort | O(n) | O(n) | Fastest — uses frequency as index |