core practice · coding problem
Top K Frequent Elements
LeetCode #347 — Top K Frequent Elements. Solve on LeetCode, then implement here if you want it in your drill queue. https://leetcode.com/problems/top-k-frequent-elements/
The mechanism
A heap gives you the min or max in O(1) and re-balances in O(log n). Whenever a problem says "top k", "k-th largest", or "merge k sorted", a heap of size k is usually the answer — far cheaper than sorting everything.
Expected evidence
Pass all LeetCode test cases for this problem.
Try this drill in the practice workspace →
Hints when you need them
- Pattern hint: heap.
- Start with brute force, then optimize time/space.
- Write down invariants before coding.
Watch for these mistakes
- Sorting the whole input when a size-k heap suffices
- Inverting heap polarity: top-k smallest wants a size-k max-heap (evict the largest), top-k largest wants a size-k min-heap
- Forgetting most languages give a min-heap by default