Heaps and priority queues
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Describe the heap property and the array representation of a heap.
- State the cost of push, pop and peek.
- Use a heap for top-k and streaming median problems.
Overview
#A heap is a complete tree with an order rule
A binary heap is a complete binary tree stored in an array. In a min-heap each parent is smaller than or equal to its children, so the smallest element is at the root. A max-heap reverses the rule.
Because the tree is complete, it maps to an array without gaps: for index i, the children are at 2i + 1 and 2i + 2, and the parent is at floor((i - 1) / 2).
Costs
| Operation | Cost |
|---|---|
| peek (root) | O(1) |
| push | O(log n) |
| pop | O(log n) |
Push appends then sifts up. Pop moves the last element to the root then sifts down. Both touch at most one path of length log n.
Top-k with a heap
To keep the k largest values seen so far, maintain a min-heap of size k. Push each value; when the heap exceeds k, pop the smallest. What remains are the k largest. This is O(n log k) time and O(k) space, better than sorting everything when k is small.
Streaming median with two heaps
Keep a max-heap for the lower half and a min-heap for the upper half. After each insert, rebalance so the sizes differ by at most one. The median is the top of the larger heap, or the average of both tops when the sizes are equal. Each insert is O(log n), and the median is O(1).
When a heap is not the answer
If you need the fully sorted order, sort instead. If you need fast search by value, use a hash map. A heap gives fast access to the extreme element, not to arbitrary elements.
Practice next
- Find the k largest elements using a min-heap of size k.
- Explain how two heaps maintain a running median.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
In a min-heap stored as [1, 3, 2, 7, 4], what are the children of the root at index 0?
starter.javascript// children of i are 2i + 1 and 2i + 2Reveal the reference answer
reference.javascriptIndex 1 holds 3 and index 2 holds 2, so the children are 3 and 2. The root 1 is smaller than both, satisfying the min-heap property.Authored expected output: 3 and 2
The array layout encodes the complete tree without pointers.
Exercise 2Implement
Describe the algorithm, in steps, to return the k largest values from a stream using one heap.
starter.textfor each value: ...Reveal the reference answer
reference.textMaintain a min-heap of size at most k. For each value, push it onto the heap. If the heap size exceeds k, pop the smallest. After processing all values, the heap contains exactly the k largest.Authored expected output: Min-heap of size k; push each value and pop the smallest when size exceeds k.
The smallest of the current candidates is always at the root, so it is the one to discard.
Exercise 3Explain
Explain why a heap is preferred over full sorting for a top-k query.
Reveal the reference answer
reference.textFull sorting costs O(n log n) and orders every element. A size-k heap costs O(n log k) and only keeps the k extremes, which is cheaper when k is much smaller than n and uses only O(k) extra space.Authored expected output: O(n log k) versus O(n log n), with O(k) extra space.
Matching the data structure to the exact question avoids unnecessary work.
Common misconceptions
#- A heap is fully sorted. Only the root is guaranteed to be the extreme; the rest have a weaker order.
- A heap supports fast search for any value. Finding an arbitrary value is O(n).
- A priority queue is different from a heap. A heap is the usual implementation of a priority queue.
Follow-up practice
#- dsa-from-zero-graphs-and-traversal
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.