Basic Heap Questions
Six warm-up exercises to lock in heap operations before you take on the interview problems. Each one tests a different muscle β the heap property, the index arithmetic, the build vs push tradeoff, the size-K trick.
If you can do these in your head, the practice problems will feel mechanical.
1. Is this a valid min-heap?
For an array to represent a valid min-heap, every parent at index i must be β€ both arr[2i+1] (left child) and arr[2i+2] (right child) β for every index that has children.
Check [3, 5, 9, 6, 8, 20, 10, 12, 18, 9]:
2. Trace this sequence on an empty min-heap
Start with []. Apply: push(5), push(3), push(8), push(1), pop(), push(2), pop(), pop().
What does the heap look like at each step? What does each pop return?
3. Build a max-heap from [4, 10, 3, 5, 1] β but two ways
Compare cost: building by n successive pushes vs heapify in place.
4. Whatβs at index 5 in a complete binary tree of 11 nodes?
If the tree is stored at indices 0..10, where is the node at array index 5? Who is its parent? Children?
5. K smallest using a heap β which kind?
You want the K smallest elements of a stream. Should you use a min-heap or a max-heap? What size?
6. After this max-heap pop, what does the heap look like?
Start with [20, 15, 17, 8, 10, 5, 12] (max-heap). Pop the root. Show the heap after the operation.
Quick check
Now play with it
The interactive heap from the Introduction page is right here, too. Try the exercises above, then make your own β push 10 random values, then pop them all and watch the sorted output emerge.
Ready for the interview classics? Head to Practice Questions.