Binary Heap
DSA · Heaps
Theory
A binary heap is a complete binary tree stored in an array that satisfies the heap property: in a min-heap every parent is smaller than or equal to its children, so the minimum is always at index 0. Inserting appends the item at the end and "sifts it up"; removing the minimum moves the last item to the root and "sifts it down". Both take O(log n), and building a heap from n items takes O(n).
Why we use it
Heaps give constant-time access to the smallest (or largest) item with logarithmic updates, which is exactly what priority queues need.
When to use it
Use heaps for priority queues, scheduling, Dijkstra's algorithm, running medians, merging k sorted lists and top-k problems.
How it works
- Insert at the end of the array
- Parent > new value? (min-heap)? Yes: Swap with parent (sift up). No: Stop.
- Pop: move last item to root
- Sift down: swap with the smaller child until ordered
- Root is always the minimum
Syntax
Array layout: parent(i) = (i-1)//2, children 2i+1 and 2i+2
push: append, sift up O(log n)
pop: swap root with last, remove, sift down O(log n)
peek: heap[0] O(1)Example
class MinHeap:
def __init__(self):
self.a = []
def push(self, x):
a = self.a
a.append(x)
i = len(a) - 1
while i > 0 and a[(i - 1) // 2] > a[i]:
p = (i - 1) // 2
a[i], a[p] = a[p], a[i]
i = p
def pop(self):
a = self.a
a[0], a[-1] = a[-1], a[0]
smallest = a.pop()
i = 0
while True:
l, r, m = 2 * i + 1, 2 * i + 2, i
if l < len(a) and a[l] < a[m]: m = l
if r < len(a) and a[r] < a[m]: m = r
if m == i: break
a[i], a[m] = a[m], a[i]
i = m
return smallest
h = MinHeap()
for x in [7, 2, 9, 4, 1, 8]:
h.push(x)
print("Heap array:", h.a)
print("Removed in order:", [h.pop() for _ in range(6)])Key points
- Complete binary tree stored in an array
- Min-heap: parent <= children
- push and pop are O(log n)
- Python heapq implements a min-heap