Heaps & priority queues
Solve top-k and merge-k problems.
By Invicly Tech, , in Interview Preparation. About 12 minutes to read.
In short
A heap always keeps the smallest (or largest) element at the top, with O(log n) insert and remove. It is the go-to structure for top-k, k-th largest and merge-k problems.
Explained simply
A heap is a structure that always knows its smallest item (or its largest, if you set it up that way). Think of a hospital waiting room. People do not leave in arrival order; the most urgent patient is always seen next. Adding a person or calling the next one is quick, even when the room is full.
In code this idea is called a priority queue. In Java it is PriorityQueue, and in Python it is the heapq module. Both are min-heaps by default: the smallest value comes out first.
A heap is not fully sorted. It only promises that each parent is smaller than its children. That weaker promise is exactly why it is fast: adding or removing an item costs O(log n), while keeping a whole list sorted would cost much more per change.
Interviews use heaps for "top k" questions, merging many sorted lists, scheduling tasks, finding a running median, and inside Dijkstra's shortest path algorithm. When you hear "k largest", "k closest" or "next smallest", think heap.
Press Play on a diagram to walk through it one step at a time.
- Step 1Push each item
heappush costs O(log k)
- Step 2Too big? Pop
If size exceeds k, remove the smallest
- Step 3Heap holds top k
Only the k largest survive
- Step 4Read the root
heap[0] is the k-th largest
- 3
- 5
- 4
- 2
- 8
- 1Seed the heap
Push the head of each of the k lists
- 2Pop the smallest
It is the next node of the answer
- 3Append it
Link it after the tail of the result
- 4Push its successor
The next node from the same list, if any
- 5Repeat until empty
N nodes x O(log k) each
In depth
How a heap lives inside an array
A heap is a complete binary tree: every level is full except maybe the last, which fills from the left. Because there are no gaps, it can be stored in a plain array with no pointers. For the node at index i, the children are at 2i + 1 and 2i + 2, and the parent is at (i - 1) / 2, rounded down.
To add an item, put it at the end of the array and sift it up: while it is smaller than its parent, swap them. The tree has about log2(n) levels, so this takes at most O(log n) swaps. Peeking at the minimum is just reading index 0, which is O(1).
- Children of i: 2i + 1 and 2i + 2
- Parent of i: (i - 1) / 2
- Height is about log2(n), so pushes are O(log n)
- 1Append at the end
[2, 3, 5, 4, 1], new item at index 4
- 2Compare with parent
Parent of 4 is index 1, value 3
- 3Swap up
[2, 1, 5, 4, 3], item now at index 1
- 4Compare again
Parent is index 0, value 2
- 5Swap up
[1, 2, 5, 4, 3], item reaches the root
Popping, and why heapify is O(n)
To remove the minimum, take index 0, move the last item into its place, and sift it down: swap it with its smaller child until both children are bigger. That is O(log n).
Building a heap from n items by pushing one at a time costs O(n log n). Heapify is smarter: it sifts down every parent, starting from the last parent and moving back to the root. Half the nodes are leaves and never move. A quarter move at most one level, an eighth at most two, and so on. That sum adds up to O(n). Use heapq.heapify(list) in Python, or new PriorityQueue(collection) in Java, which also builds the heap in linear time.
Java PriorityQueue in practice
new PriorityQueue() gives a min-heap of comparable items. Pass a comparator for anything else: Comparator.reverseOrder() for a max-heap, or a lambda such as (a, b) -> Integer.compare(a[1], b[1]) to order arrays by their second value. Avoid the shortcut a - b: it overflows when values are large or have opposite signs, and the heap silently becomes wrong.
Know the costs: offer and poll are O(log n), peek is O(1), but remove(object) and contains are O(n) because the heap must scan. Iterating over a PriorityQueue or printing it does not give sorted order. In Python, heapq has no comparator, so push tuples like (priority, counter, item); the counter breaks ties so Python never compares the items themselves.
- Integer.compare(a, b) instead of a - b
- remove(obj) is O(n): avoid it in loops
- Printing a heap does not show sorted order
Two heaps for a running median
To get the median of a stream of numbers at any moment, split the numbers into two halves. A max-heap holds the smaller half, so its top is the largest of the small numbers. A min-heap holds the bigger half, so its top is the smallest of the big numbers. Keep their sizes equal, or let the max-heap hold one extra.
Each new number goes into one heap, and then you move one top across if the halves are out of order or out of balance. The median is either the top of the max-heap (odd count) or the average of both tops (even count). Adding costs O(log n) and reading the median costs O(1). The same two-heap idea solves sliding window median and IPO-style problems.
- Holds the smaller numbers
- Top = largest small number
- May hold one extra item
- Holds the bigger numbers
- Top = smallest big number
- Never bigger than the low half
Heap, sort or quickselect for top k?
There are three common ways to find the k largest of n items. Sorting is simplest: O(n log n), fine for small inputs. A size-k min-heap costs O(n log k) and only O(k) memory, and it works on a stream where you never see all the data at once. Quickselect, the partition step of quicksort, finds the kth largest in O(n) on average but O(n^2) in the worst case, and needs all data in memory.
For Top K Frequent Elements there is a fourth option: bucket sort by frequency. A value can appear at most n times, so make n + 1 buckets and read them from the highest. That is O(n). In an interview, give the heap solution first, then mention the faster options and their trade-offs.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Learn heap operations and their costs~1h
- 2Use PriorityQueue with comparators~1h
- 3Practice: Kth Largest Element, Top K Frequent~1h
- 4Practice: Merge K Sorted Lists~1h
Key points
- Push and pop are O(log n); peeking the top is O(1); heapify is O(n).
- Top-k with a size-k heap costs O(n log k), better than sorting when k is small.
- Python heapq is a min-heap; negate values to simulate a max-heap.
- In Java, new PriorityQueue<>(Comparator.reverseOrder()) gives a max-heap.
Key terms
Tap a card to flip it. 0/4 known
Examples
import heapq
def kth_largest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest
return heap[0] # O(n log k)
# Java: PriorityQueue<Integer> pq = new PriorityQueue<>();Top K Frequent Elements: [1, 1, 1, 2, 2, 3], k = 2
Step 1: count with a map: 1 appears 3 times, 2 twice, 3 once. Step 2: keep a min-heap of at most k values, ordered by count. Push 1, push 2. Push 3: the size is now 3, so poll the least frequent, which is 3. Step 3: the heap holds 1 and 2, the answer. Counting is O(n); the heap work is O(m log k) for m distinct values.
int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : nums) count.merge(x, 1, Integer::sum);
// min-heap by count: the least frequent value sits on top and is evicted first
PriorityQueue<Integer> heap =
new PriorityQueue<>((a, b) -> Integer.compare(count.get(a), count.get(b)));
for (int x : count.keySet()) {
heap.offer(x);
if (heap.size() > k) heap.poll();
}
int[] out = new int[k];
for (int i = k - 1; i >= 0; i--) out[i] = heap.poll(); // most frequent first
return out;
}Merge K Sorted Lists: [1, 4, 5], [1, 3, 4], [2, 6]
The heap starts with the three heads: 1, 1, 2. Pop a 1, append it, push its next node 4. Pop the other 1, push 3. Pop 2, push 6. Pop 3, push 4. Now pop 4, 4, 5 and 6 in turn. Result: 1, 1, 2, 3, 4, 4, 5, 6. The heap never holds more than k nodes, so each step is O(log k) and the total is O(N log k) for N nodes. A dummy head node avoids a special case for the first append.
ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap =
new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
for (ListNode head : lists) if (head != null) heap.offer(head);
ListNode dummy = new ListNode(0), tail = dummy;
while (!heap.isEmpty()) {
ListNode node = heap.poll(); // smallest head among the lists
tail.next = node;
tail = node;
if (node.next != null) heap.offer(node.next);
}
return dummy.next; // O(N log k) time, O(k) heap space
}Quick reference
- Array heap: children of i are 2i + 1 and 2i + 2; the parent is (i - 1) / 2
- peek O(1); offer and poll O(log n); heapify O(n); remove(obj) and contains O(n)
- k largest: keep a size-k min-heap; k smallest: keep a size-k max-heap
- Comparators: use Integer.compare(a, b), not a - b, to avoid overflow
- Running median: max-heap for the low half, min-heap for the high half
- Python heapq ties: push (priority, counter, item) so items are never compared
- Iterating a PriorityQueue is not sorted; poll repeatedly to get items in order
Common mistakes
- Using a max-heap of all n items when a size-k min-heap suffices.
- Assuming the heap list is fully sorted; only the root is guaranteed.
- Pushing tuples with uncomparable second items in Python.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Last Stone Weight: repeatedly smash the two heaviest stones. If they differ, the difference goes back in. Return the last weight, or 0.
- Exercise 2medium
K Closest Points to Origin: return the k points nearest to (0, 0).
- Exercise 3hard
Find Median from Data Stream: support addNum(num) and findMedian().
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is a heap the same thing as a priority queue?
- A priority queue is the idea: a queue that always serves the most important item. A binary heap is the usual way to build one, which is why the two words are often used as if they were the same.
- Why is heapify O(n) and not O(n log n)?
- Heapify sifts down from the bottom up. Most nodes are near the leaves and move only a step or two, and only a few nodes near the top can move far, so the total work adds up to linear time.
- Can I change the priority of an item already in the heap?
- Java's PriorityQueue and Python's heapq have no fast update. The usual trick is lazy deletion: push a new entry with the new priority and skip old entries when you pop them, exactly as Dijkstra's algorithm does.
- Should I use a heap or just sort in an interview?
- If k is small compared with n, or the data is a stream, a heap is better and shows you know the trade-off. If you need everything in order anyway, sorting is simpler and perfectly fine.