Core Data Structures
Heaps & Priority Queues
A binary heap is a complete binary tree stored implicitly in an array, maintaining the invariant that every parent is smaller (min-heap) or larger (max-heap) than its children. It is the standard implementation of the priority queue ADT:
O(log n) insert, O(log n) extract-min/max, O(1) peek.- Complete binary tree stored in an array: node at index
ihas children at2i+1and2i+2, parent at(i-1)/2— no pointers needed - Min-heap property: every parent ≤ both children (recursively) — the minimum is always at the root, not necessarily anywhere else specific
insert(sift-up) andextractMin(sift-down) are bothO(log n);peekMinisO(1)- Building a heap from n unordered elements is
O(n), notO(n log n)— bottom-up heapify does less work than n sequential inserts - Java's
PriorityQueueis a min-heap by default; pass aComparatorfor max-heap or custom ordering - A heap is only "sorted" at the root — it is not a fully sorted structure, which is exactly what makes building it fast
| Operation | Cost | Mechanism |
|---|---|---|
peek (min/max) | O(1) | Always at index 0 |
insert | O(log n) | Append at end, sift up |
extractMin/extractMax | O(log n) | Swap root with last, remove last, sift down |
heapify (build from n elements) | O(n) | Bottom-up sift-down from last internal node |
int[] heap; int size;
void siftUp(int i) {
while (i > 0 && heap[(i - 1) / 2] > heap[i]) {
swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
int extractMin() {
int min = heap[0];
heap[0] = heap[--size]; // move last element to root
siftDown(0);
return min;
}
void siftDown(int i) {
while (true) {
int l = 2 * i + 1, r = 2 * i + 2, smallest = i;
if (l < size && heap[l] < heap[smallest]) smallest = l;
if (r < size && heap[r] < heap[smallest]) smallest = r;
if (smallest == i) break;
swap(i, smallest);
i = smallest;
}
}Heapsort (Heapsort) is exactly "build a heap in O(n), then extract the minimum n times" — O(n) + n·O(log n) = O(n log n) total, in place, with no extra memory. This is also the mechanism behind the top-K interview pattern (Heap Top K Pattern): maintain a heap of size k instead of sorting everything, turning an O(n log n) full sort into O(n log k).