LeetCode 347 ·
Medium
Top K Frequent Elements
Return the k most frequent elements.
Try it
Step through the core mechanic. The simulator below runs the heap shape this problem is built on.
Walk the pattern
No dedicated step-through for this one yet. The shape is Heap — its pattern page has the interactive walkthrough, the reference implementation, and a five-problem progression that this problem sits inside.
The approach
Count with a hash map, then bucket-sort by frequency (index = count) for O(n), or push counts through a size-k heap for O(n log k).
| Aspect | Value |
|---|---|
| Pattern | Heap |
| Recognise it by | Top-K by count. |
| Time complexity | O(n) |
| Space complexity | O(n) |
| Difficulty | Medium |
Who asks it
Companies known to ask this problem, from public LeetCode company-tag aggregations. A signal of where to expect it, not a guarantee.