Top K Elements Pattern
The Top K Elements pattern uses a heap of size k to track the largest, smallest, or most frequent values in a stream or array without sorting the whole input. It answers "top k" and "k closest" questions in O(n log k) time and O(k) space, which beats the O(n log n) cost of a full sort when k is small.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Complexity
- Time
- O(n log k)
- Space
- O(k)
When to use Top K Elements
- The problem asks for the k largest, smallest, or most frequent elements in a collection.
- You need the k points closest to the origin (or any reference point) in a list of coordinates.
- You need the kth largest element in a stream where elements arrive one at a time.
- You want to avoid the full O(n log n) sort cost when k is much smaller than n.
- You need to reorganize or rearrange characters / tasks based on top frequencies.
Template
function topKLargest(nums, k) {
const minHeap = new MinHeap();
for (const num of nums) {
minHeap.push(num);
if (minHeap.size > k) {
minHeap.pop();
}
}
return minHeap.toArray();
}Example LeetCode problems
| # | Problem | Difficulty | Frequency |
|---|---|---|---|
| 215 | Kth Largest Element in an Array | medium | foundational |
| 347 | Top K Frequent Elements | medium | company favorite |
| 973 | K Closest Points to Origin | medium | company favorite |
| 703 | Kth Largest Element in a Stream | easy | frequently asked |
| 692 | Top K Frequent Words | medium | frequently asked |
| 451 | Sort Characters By Frequency | medium | classic |
| 621 | Task Scheduler | medium | company favorite |
| 767 | Reorganize String | medium | frequently asked |
Common mistakes
- Using a max-heap of size n when a min-heap of size k would suffice; the larger heap costs O(n log n) and defeats the pattern's purpose.
- Pushing first and then conditionally popping vs comparing the heap top before pushing — both work, but mixing the two creates off-by-one heap sizes.
- Forgetting to bound the heap; if you never pop, you end up with a fully-sorted output and lose the k-bound on memory.
- On ties in Top K Frequent Words, ignoring the secondary lexicographic sort and emitting the wrong order.
- Using `Array.prototype.sort` as a shortcut and writing O(n log n) when the interviewer explicitly asks for better than full-sort complexity.
Frequently asked questions
Why use a min-heap to find the k largest elements?
The min-heap of size k stores exactly the top-k seen so far. When a new element arrives, you compare it to the heap's minimum (the root). If the new element is larger, evict the minimum and insert. The heap always contains the current top-k.
Can I use quickselect instead of a heap?
Yes. Quickselect finds the kth element in O(n) average time and lets you partition the array around it for the rest of the top-k. The heap version is more cache-friendly, easier to write under interview pressure, and works for streaming input that quickselect cannot handle.
What is the difference between Top K Frequent Elements and just sorting by frequency?
Sorting by frequency is O(n log n). The heap version is O(n log k). When the array has 1M unique elements and you only need the top 10, the heap wins by orders of magnitude.
How does Task Scheduler relate to this pattern?
Task Scheduler uses a max-heap of frequencies to repeatedly pick the most-needed task while respecting the cooldown gap. It's a Top K variant where k changes dynamically as tasks are scheduled and re-inserted.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill the Top K Elements pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →