Heap#
A heap is a complete binary tree satisfying the heap property: in a min-heap, every parent ≤ its children; in a max-heap, every parent ≥ children. The extremum (min or max) is always at the root.
When to use a heap#
| Scenario | Why heap |
|---|---|
| K-th largest / smallest | Size-k heap |
| Merge K sorted lists | Min-heap of heads |
| Median from stream | Two heaps (max left, min right) |
| Dijkstra / Prim | Extract-min on edge weights |
| Scheduling by priority | Priority queue |
Prefer heapq in Python (min-heap). Negate values to simulate max-heap.
Complexity (n elements)#
| Operation | Time |
|---|---|
Insert (heappush) |
O(log n) |
| Extract min/max | O(log n) |
| Peek min/max | O(1) |
| Build heap from array | O(n) (heapify) |
| Heap sort | O(n log n) |
| Space | O(n) |
Min-heap structure#
Python heapq (use this in interviews)#
import heapq
heap = [3, 1, 4]
heapq.heapify(heap) # O(n) build
heapq.heappush(heap, 2) # O(log n)
smallest = heapq.heappop(heap) # O(log n)
k_largest = heapq.nlargest(k, nums)
Pitfalls:
heapqis a min-heap only — negate values for max-heap (heappush(heap, -x)).- Tuple comparison is lexicographic:
(priority, tie_breaker, payload)when priorities tie. - For streaming median, use two heaps: max-heap for lower half, min-heap for upper half; rebalance so sizes differ by at most 1 (LC 295).
K-th element decision: heapq.nlargest(k, nums) is O(n log k) and fine for one-off queries; maintain a size-k heap when processing a stream; quickselect is O(n) average for a single K-th on a static array.