DSA/Lesson 7 of 11/5 min read
Heaps and Tries
Binary heaps, heapify, heap sort, top-k and median patterns, plus tries for prefix search and autocomplete.
On this page
Binary Heap
A complete binary tree that satisfies the heap property. Because it is complete, it is stored compactly in an array with no pointers.
For node at index i (0-based):
parent = (i - 1) // 2
left = 2i + 1
right = 2i + 2Min-Heap
Every parent is less than or equal to its children. The minimum is at the root. Python heapq is a min-heap.
Max-Heap
Every parent is greater than or equal to its children. In Python, push negated values to simulate it. Java PriorityQueue is a min-heap by default; pass Collections.reverseOrder() for max.
| Operation | Complexity |
|---|---|
| Peek min or max | O(1) |
| Insert (push) | O(log n) |
| Extract (pop) | O(log n) |
| Build heap from n items | O(n) |
| Search arbitrary value | O(n) |
Insert: sift up
Append at the end, then swap with the parent while the heap property is violated.
Extract: sift down
Move the last element to the root, then swap it with the smaller child (min-heap) until it settles.
def sift_down(a, i, n):
while True:
smallest, l, r = i, 2 * i + 1, 2 * i + 2
if l < n and a[l] < a[smallest]: smallest = l
if r < n and a[r] < a[smallest]: smallest = r
if smallest == i:
return
a[i], a[smallest] = a[smallest], a[i]
i = smallestHeapify
Turning an arbitrary array into a heap: call sift_down on every non-leaf from the last one (n // 2 - 1) back to the root.
It looks like O(n log n), but it is O(n): most nodes are near the bottom and sift down only a short distance. The sum n/4 * 1 + n/8 * 2 + n/16 * 3 + ... converges to O(n).
Heap Sort
- Build a max-heap in
O(n). - Repeatedly swap the root with the last element, shrink the heap by one, and sift down.
| Property | Value |
|---|---|
| Time | O(n log n) in all cases |
| Space | O(1) |
| Stable | No |
In practice it is slower than quicksort due to poor cache locality, but it guarantees O(n log n). Introsort (C++ std::sort) falls back to heap sort when quicksort recursion gets too deep.
Top K
Find the k largest elements of n items:
- Sort:
O(n log n). - Min-heap of size k: push each item, pop when size exceeds k.
O(n log k)time,O(k)space. Works on streams. - Quickselect:
O(n)average,O(n^2)worst.
import heapq
def top_k(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return heapNote the inversion: use a min-heap to keep the k largest, because the root is the weakest candidate to evict.
Related: k closest points, top k frequent words, kth largest element, merge k sorted lists (O(N log k)).
Two Heaps
Running median of a stream:
low: max-heap with the smaller half;high: min-heap with the larger half;- keep sizes balanced (differ by at most 1).
Median is the top of the larger heap, or the average of both tops. Insert is O(log n), median is O(1).
Also used for sliding window median and the IPO / maximize capital problem.
Trie
A prefix tree: each node represents a prefix, and each edge is a character. Words sharing a prefix share a path.
root
/ \
c d
| |
a o
/ \ |
t* r* g** marks end-of-word. This trie stores cat, car, dog.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end = True
def starts_with(self, prefix):
node = self.root
for ch in prefix:
if ch not in node.children:
return False
node = node.children[ch]
return True| Operation | Complexity (L = word length) |
|---|---|
| Insert | O(L) |
| Search word | O(L) |
| Prefix search | O(L) |
| Space | O(total characters * alphabet) worst |
Prefix Tree vs hash set
| Trie | Hash set | |
|---|---|---|
| Exact lookup | O(L) | O(L) average (hashing the key) |
| Prefix queries | Yes | No |
| Sorted iteration | Yes (DFS) | No |
| Memory | Higher | Lower |
Where tries are used
- Autocomplete and search suggestions.
- Spell checkers and word games (Boggle, word search II).
- IP routing with longest prefix match.
- Bitwise trie for maximum XOR of two numbers.
Pitfall: memory blow-up with large alphabets. Use a hash map per node instead of a fixed 26 or 256 array, or a compressed radix tree.
Quick revision
- Heap: complete binary tree in an array; parent
(i-1)//2, children2i+1,2i+2. - Push and pop
O(log n), peekO(1), build heapO(n). - Heap sort:
O(n log n), in place, not stable. - Top k largest: min-heap of size k,
O(n log k). - Running median: max-heap for lower half, min-heap for upper half.
- Trie:
O(L)insert and lookup, best for prefix queries and autocomplete.