Recursion, trees and heaps · mid
Heaps and priority queues
A heap is a tree stored in an array that keeps the smallest (or largest) item on top, giving O(log n) push and pop and O(1) peek. Use it for top-k, merging sorted lists and 'always take the best next item'.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Array layout: the children of index i are 2i + 1 and 2i + 2; the parent is floor((i - 1) / 2).
- push: add at the end, then sift up while smaller than the parent. pop: take the root, move the last item to the root, then sift down toward the smaller child. Building a heap from n items with heapify is O(n).
- Use the library heap (see the toolkit topic): Java PriorityQueue (min-heap), Python heapq (min-heap in a list), C++ priority_queue (max-heap). Be ready to write sift up and sift down by hand if asked.
- Top k largest: keep a MIN-heap of size k (O(n log k)); the root is the k-th largest.
- Merge k sorted lists: a heap that holds the current head of each list, O(N log k).
- Ties: store (priority, insertion number, item) so equal priorities come out in insertion order and the items themselves are never compared (this is also what the Python docs advise).
- If n is small or the interviewer allows it, sorting is fine; say the trade-off. Quickselect gives the k-th largest in O(n) on average.
The red pen
Common traps: mistake → fix
Mistake: Sorting after every insert is a priority queue
Fix: that is O(n log n) per insert.
Mistake: Top-k largest needs a max-heap of all items
Fix: a min-heap of size k is cheaper in memory and time.
Mistake: Heap order means the array is sorted
Fix: only the parent-child relation holds.
Easy to hard
Questions interviewers ask, easy to hard
- Find the k-th largest element. What is the complexity?
- Top k frequent elements.
- Merge k sorted lists.
- How does a heap push work inside, and why is it O(log n)?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.