“Find the 3rd largest.” “Show the top 10 trending posts.” “Return the K closest restaurants.” Whenever a question says top K or Kth, there's a tool built for it: the heap (also called a priority queue).
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stacknext greater element
- 8Heap / Top-Ktop K, Kth largest
- 9Tree Patternsdepth, paths, levels
- 10Grid BFS & Topological Sortislands, dependencies
- 11Backtrackingall combinations
- 12DP Patternscount ways, min cost
The club bouncer story
A club fits only 3 people. The bouncer doesn't compare a newcomer with everyone inside, only with the weakest person inside. Stronger? The weakest leaves and the newcomer enters. Weaker? Turned away. The bouncer is the top of a min-heap. Watch it run a leaderboard:
🏆 Keep the top 3 scores as they stream in
Min-heap (top 3)
top = the weakest of the best · compare every newcomer with it only
Scores arrive one by one. We keep only the top 3 in a min-heap: the smallest of them always sits on top.
Scores seen: 0 · comparisons with the top: 0
Sorting every score would cost O(n log n) and keep everything in memory. A heap of size K needs only K slots and O(log K) per score, which is why it powers leaderboards, “top 10 trending” and “K closest” problems.
What a heap gives you
- Peek the top (smallest in a min-heap): O(1).
- Push a new item: O(log n).
- Pop the top: O(log n).
It's stored as a simple array shaped like a tree (like the trees from Part 8, but only the top is ordered), so you never build it by hand: every language has one built in.
🔍 Use a heap when you see
- ✓“Top K”, “K largest / smallest”, “Kth largest”
- ✓“K closest”, “K most frequent”
- ✓Merge K sorted lists or streams
- ✓Running median, scheduling the next job
🚫 Don't use it when
- ✗You need everything in sorted order (just sort)
- ✗“Next greater” for each item (monotonic stack)
- ✗Only the single max or min (one variable is enough)
The template
heap = [] # min-heap
for x in nums:
push(heap, x)
if len(heap) > K:
pop(heap) # kick out the weakest of the top K
# heap now holds the K largest; heap[0] is the Kth largest⚡ Memory tricks
- 1
“K largest → min-heap. K smallest → max-heap.”
Keep the opposite heap so the top is the one to beat.
- 2
“The bouncer checks the weakest inside”
Compare each newcomer with the top only.
- 3
“Size K, cost log K”
O(n log k) time, O(k) space.
- 4
“C++ flips it”
priority_queue is a max-heap by default; use greater<> for a min-heap.
Code: Kth largest and top K frequent
Outputs in the comments come from running the code.
import heapq
from collections import Counter
def kth_largest(nums, k):
"""Keep a min-heap of the k biggest; its top is the k-th largest."""
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # kick out the smallest of the top k
return heap[0]
def top_k_frequent(nums, k):
"""The k most common numbers, most common first."""
counts = Counter(nums)
heap = [] # (count, number), smallest count on top
for num, c in counts.items():
heapq.heappush(heap, (c, num))
if len(heap) > k:
heapq.heappop(heap)
return [num for c, num in sorted(heap, reverse=True)]
print(kth_largest([3, 2, 1, 5, 6, 4], 2)) # 5
print(top_k_frequent([1, 1, 1, 2, 2, 3], 2)) # [1, 2]One pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| Kth Largest Element in an Array | Min-heap of size K | Medium |
| Kth Largest in a Stream | Same heap, kept between calls | Easy |
| Top K Frequent Elements | Count with a hash map, then heap by count | Medium |
| K Closest Points to Origin | Max-heap of size K by distance | Medium |
| Merge K Sorted Lists | Min-heap of list heads | Hard |
| Find Median from Data Stream | Two heaps: lower and upper half | Hard |
| Meeting Rooms II | Min-heap of meeting end times | Medium |
🎯 Spot the pattern: is it a heap?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Return the K most frequent words in a document.
2. Merge K sorted lists into one sorted list.
3. Find the median of a number stream at any moment.
4. For each day, find the next warmer day.
5. Find K points closest to the origin.
🧠 PATH memory card
Remember heaps and top-K for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
A club for the top 3. The bouncer only compares each newcomer with the weakest person inside.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Top-K club: the bouncer only checks the weakest inside”
- Top-K club→A heap that holds exactly K items
- Bouncer→The top of the heap
- Weakest inside→For K largest, use a min-heap: its top is the smallest of the K
- Beat them or go home→If new > top: pop the top, push the new item
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Top 3 of[72, 85, 64, 91, 78, 95]: fill 72, 85, 64 → 91 beats 64 · 78 beats 72 · 95 beats 78 → heap holds 85, 91, 95, top 85 = 3rd largest. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 6 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Using a max-heap for the K largest. You'd have to pop everything else; use a min-heap of size K.
- Letting the heap grow to n. Pop as soon as it passes K, or you lose the O(log k) benefit.
- Forgetting C++'s default.
priority_queue<int>is a max-heap.
Where to go next
Heaps are trees in disguise. Next, the real tree questions interviewers love: depth, paths, levels and the lowest common ancestor, all from two moves: binary tree patterns (DFS and BFS).
Key takeaways
- ✓A heap keeps the smallest (or biggest) item on top: peek O(1), push/pop O(log n).
- ✓Top K largest → min-heap of size K; top K smallest → max-heap of size K.
- ✓Each newcomer is compared with the top only: O(n log k).
- ✓Heaps also merge K sorted lists and track a running median.
- ✓Signals: top K, Kth, K closest, K most frequent.
Frequently asked questions
What is a heap in simple words?
A heap is a tree-shaped structure that always keeps the smallest item (min-heap) or the biggest item (max-heap) on top, ready to read in O(1). Adding or removing an item takes O(log n). In code it's usually called a priority queue.
How do you find the Kth largest element with a heap?
Keep a min-heap of size K. Push each number; if the heap grows past K, pop the smallest. At the end the heap holds the K largest numbers and its top is the Kth largest. Time O(n log k), space O(k).
Why use a min-heap to find the largest elements?
Because the top of a min-heap is the weakest member of your top K. Every new number only needs to beat that one. It sounds backwards at first, which is why it's an interview favourite.
Is a heap faster than sorting?
Sorting everything is O(n log n). A size-K heap is O(n log k), which is much faster when K is small, and it works on a live stream where you can't sort everything at once.
What's the difference between heapq in Python, PriorityQueue in Java and priority_queue in C++?
Python's heapq and Java's PriorityQueue are min-heaps by default. C++'s priority_queue is a max-heap by default; pass greater<int> to make it a min-heap. The ideas are the same.
🧠 Quick check: heaps and top-K
1. To keep the 3 LARGEST numbers from a stream, which heap and size?
2. Min-heap of the top 3 holds 82, 91, 95. A score of 80 arrives. What happens?
3. Time complexity of finding the Kth largest of n numbers with a size-K heap?
4. Which problem is a heap problem?
Checking your access…