68 / 75
Medium
Top K Frequent Elements
#68arrayhash-tableheapbucket-sortquickselect
Count frequencies with HashMap, use min-heap of size k to track top k elements.
Example:
Input:
nums=[1,1,1,2,2,3], k=2Output:
[1,2] (most frequent elements)Common Mistakes:
- Using max-heap and keeping all elements (inefficient O(n log n))
- Not comparing by frequency in heap comparator
- Sorting entire array when heap suffices
- Not handling ties in frequency correctly
Notes:
Time O(n log k) with heap. Space O(n). Can optimize to O(n) with bucket sort or quickselect. Follow-up asks for better than O(n log n).
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Count frequencies with HashMap, use min-heap of size k to track top k elements.
Example:
Input:
nums=[1,1,1,2,2,3], k=2Output:
[1,2] (most frequent elements)Common Mistakes:
- Using max-heap and keeping all elements (inefficient O(n log n))
- Not comparing by frequency in heap comparator
- Sorting entire array when heap suffices
- Not handling ties in frequency correctly
Notes:
Time O(n log k) with heap. Space O(n). Can optimize to O(n) with bucket sort or quickselect. Follow-up asks for better than O(n log n).
68/75
Top K Frequent Elements