Q&A-5How do min-heaps and max-heaps differ in their invariants, how do peek, push, and pop operate on each, and what are their exact time and space complexities?
Answer
A binary min-heap enforces parent(i) <= node(i) for every node except the root; a max-heap enforces parent(i) >= node(i). Both are complete binary trees stored in a contiguous array, so for zero-based indexing the left child of i is 2i + 1, the right child is 2i + 2, and the parent is floor((i - 1) / 2). The invariant is only local, it says nothing about the order of siblings or cousins, which is exactly why the extreme is cheap to read and everything else is not.
The three operations are structurally identical for both; only the comparator flips.
- Peek: read index 0.
O(1)time,O(1)space. - Push: append at index
n, then sift up against the parent until the invariant holds.O(1)best case (the new key already satisfies the parent comparison),O(log n)worst case: one comparison per level on the leaf-to-root path. - Pop: move the last element to index 0, shrink by one, then sift down along the path of the extreme child (smaller child in a min-heap, larger in a max-heap).
O(log n)time,O(1)auxiliary space.
| Operation | Min-heap | Max-heap | Time | Auxiliary space |
|---|---|---|---|---|
| Peek | returns minimum | returns maximum | O(1) | O(1) |
| Push | append, sift up | append, sift up | O(log n) worst, O(1) best | O(1) |
| Pop | remove root, sift down | remove root, sift down | O(log n) | O(1) |
| Storage | array of n items | array of n items | — | O(n) total |
When a heap is the wrong structure
The heap's advantage is a cheap extreme with cheap insertion. The moment you need anything else, a different structure wins:
- Need both min and max, or arbitrary search/delete. A heap gives no ordering between siblings, so finding the max in a min-heap means scanning all leaves (indices
floor(n/2)ton-1),O(n). A balanced BST (std::multiset, JavaTreeMap) givesO(log n)peek, insert, delete, plus predecessor/successor and ordered iteration. Use it when you need more than the single extreme. - Data is static and you query repeatedly. A sorted array gives
O(1)peek at either end andO(log n)binary search, at the cost ofO(n)insertion. If you build once and read many times, sort instead of heapify. - Keys are small bounded integers. Counting sort or a bucket/radix structure gives
O(1)amortized per operation, beating the heap'slog nfactor outright. - You need decrease-key. Dijkstra and Prim want it; a plain binary heap doesn't support it, so you either use an indexed heap or push duplicates and skip stale entries on pop (lazy deletion), which trades memory for simplicity.
- You need stable FIFO tie-breaking. A heap is not stable; equal keys come out in arbitrary order. Add a sequence number to the key if order among ties matters.
A d-ary heap (say 4-ary) is a middle ground: a shallower tree speeds sift-down at the cost of more comparisons per level, and it often wins in practice on cache locality.
Standard library conventions
Python's heapq and Java's PriorityQueue are min-heaps; C++'s std::priority_queue defaults to a max-heap (std::less<T>).
import heapq
min_h = [5, 1, 8]
heapq.heapify(min_h) # [1, 5, 8]
peek_min = min_h[0] # 1, O(1)
heapq.heappush(min_h, 3) # O(log n)
extracted_min = heapq.heappop(min_h) # 1, O(log n)
# Max-heap in Python: negate numeric keys
max_h = []
for x in [5, 1, 8]:
heapq.heappush(max_h, -x)
peek_max = -max_h[0] # 8, O(1)
extracted_max = -heapq.heappop(max_h) # 8, O(log n)Negation is a workaround, not a general solution: it only works for numeric keys and breaks for arbitrary objects unless you wrap them in a reversed-comparator class. If you need a real max-heap over custom types, supply that wrapper rather than negating.
A common failure mode is reaching for the opposite extreme from a heap you already have: retrieving the maximum from a min-heap, or vice versa. That is an O(n) leaf scan, not O(1), and it silently turns a log n algorithm into a linear one. Detect it by watching for a full scan inside a loop that was supposed to be heap-driven; the fix is a second heap or a balanced BST.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.