Union-Find, Priority Queue, Heap, BST
Three structures that make 'merge groups', 'serve the biggest first' and 'keep things sorted' fast.
- maintain components with union–find (union by size, path compression)
- implement insert and delete_max for a binary heap stored in an array
- heapify and heap-sort
- insert, search and delete in a BST and explain why height matters
Union–Find: tracking connected components
Suppose edges arrive one at a time and we repeatedly ask 'are u and v connected yet?' Re-running BFS each time costs O(n + m). We want a structure that supports:
| Operation | Meaning |
|---|---|
find(x) | which component (set) does x belong to? — returns a representative |
union(x, y) | merge the components of x and y |
makeset(x) | start with each item alone |
Attempt 1 — a component array
Keep comp[x] = name of x's component. find is O(1). union must relabel one whole component: O(n). Always relabelling the smaller component helps: each element is relabelled only when its component at least doubles, so it changes label at most log₂ n times — O(m + n log n) for any sequence of unions.
Attempt 2 — parent pointers (a forest)
Store parent[x]. A root has parent[x] = x. find(x) follows parents to the root; union links one root below the other — O(1) after finding the roots. The danger: a long chain makes find O(n). Two fixes, used together:
| Trick | What it does |
|---|---|
| Union by size/rank | hang the smaller tree under the larger root, so trees stay shallow (height ≤ log n) |
| Path compression | after finding the root, point every node on the path directly at it |
With both tricks, a sequence of m operations takes O(m · α(n)) where α is the inverse Ackermann function, which is at most 4 for any n that fits in the universe. In practice: nearly constant per operation.
How many components remain?
parent = list(range(6))
def find(x):
while parent[x] != x:
x = parent[x]
return x
for a, b in [(0, 1), (2, 3), (1, 3), (4, 5)]:
ra, rb = find(a), find(b)
if ra != rb:
parent[rb] = ra
print(len({find(x) for x in range(6)}))Why does union by size keep trees shallow?
Union–Find is the key helper in which algorithm?
Priority queues
A priority queue stores items with priorities and repeatedly serves the one with the highest (or lowest) priority — hospital triage, OS schedulers, event simulation, Dijkstra. Operations: insert(x) and delete_max() (or delete_min()).
| Implementation | insert | delete_max |
|---|---|---|
| unsorted list | O(1) | O(n) |
| sorted list | O(n) | O(1) |
| heap | O(log n) | O(log n) |
With the list versions, a sequence of n inserts and n deletes costs O(n²). A heap brings it to O(n log n) — and doubles as a sorting algorithm.
Heaps
A binary heap is a complete binary tree (every level full except possibly the last, which fills left to right) in which every node's value is at least as large as its children's (max-heap). The largest value is always at the root. Because the tree is complete, we store it in an array:
| Relation | Index |
|---|---|
children of node i | 2i + 1 and 2i + 2 |
parent of node i | (i − 1) // 2 |
| height of a heap of n nodes | ⌊log₂ n⌋ |
Insert: sift up
Put the new value at the end (next free position) so the shape stays complete, then swap it upward while it is larger than its parent. At most log n swaps.
Delete max: sift down
Remove the root, move the last element to the root, then swap it downward with its larger child while it is smaller than that child. At most log n swaps.
Build a max-heap by inserting 4, 10, 3, 5, 1 in order. Final array?
a = []
for x in [4, 10, 3, 5, 1]:
a.append(x)
i = len(a) - 1
while i > 0 and a[(i - 1) // 2] < a[i]:
a[(i - 1) // 2], a[i] = a[i], a[(i - 1) // 2]
i = (i - 1) // 2
print(a)Building a heap in O(n)
Inserting n items one by one costs O(n log n). Better: put them all in an array and run sift-down from the last parent (n//2 − 1) back to the root. Most nodes are near the bottom and sift only a little, so the total is O(n).
Heap sort
Build a max-heap, then repeatedly swap the root with the last unsorted position, shrink the heap by one and sift down. Total O(n log n), in place, but not stable.
Where in a max-heap stored as an array is the smallest element?
In the array [20, 15, 18, 7, 9, 10] (a max-heap), what is the parent of the value at index 5?
How many comparisons-and-swaps does insert need in the worst case for a heap with 1,000,000 items?
Binary search trees (BST)
A sorted array searches in O(log n) but inserts in O(n). A binary search tree aims for both in O(log n). Each node holds a value, and everything in its left subtree is smaller, everything in its right subtree is larger.
Visiting left subtree, node, right subtree lists the keys in sorted order. Hence BST ⇒ sorting by inserting then traversing (the tree equivalent of quicksort).
Deletion
| Node to delete | What to do |
|---|---|
| a leaf | just remove it |
| one child | replace the node by that child |
| two children | replace its key by its in-order successor (smallest key in the right subtree), then delete that successor node (which has at most one child) |
The problem: shape depends on insertion order
Insert 1, 2, 3, 4, 5 in that order and you get a chain: height 5, every operation O(n). Insert them as 3, 1, 5, 2, 4 and the tree is balanced: height 3. Operations cost O(height), which is anywhere from log n to n.
What are the two heights printed?
class Node:
def __init__(self, k):
self.k, self.l, self.r = k, None, None
def ins(t, k):
if t is None:
return Node(k)
if k < t.k: t.l = ins(t.l, k)
else: t.r = ins(t.r, k)
return t
def h(t):
return 0 if t is None else 1 + max(h(t.l), h(t.r))
for order in ([1, 2, 3, 4, 5], [3, 1, 5, 2, 4]):
root = None
for k in order:
root = ins(root, k)
print(h(root))In a BST, where is the minimum key?
The in-order successor of node 50 in the tree built from [50, 30, 70, 60, 80] is…
The height of a BST with n nodes can be as large as…
Chapter challenge — Week 6
Which pair of operations gives Kruskal's algorithm its cycle test?
What does this program print?
a = [9, 7, 8, 3, 5] # a valid max-heap
top = a[0]
a[0] = a.pop()
i = 0
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < len(a) and a[l] > a[big]: big = l
if r < len(a) and a[r] > a[big]: big = r
if big == i: break
a[i], a[big] = a[big], a[i]
i = big
print(top, a)Insert a value into a max-heap.
A heap is stored in an array. Node at index 7: what is its parent's index?
Building a heap from n unsorted values by sift-down from the last parent costs…
What does this print? (type the exact output)
class Node:
def __init__(self, k): self.k, self.l, self.r = k, None, None
def ins(t, k):
if t is None: return Node(k)
if k < t.k: t.l = ins(t.l, k)
else: t.r = ins(t.r, k)
return t
def inorder(t): return inorder(t.l) + [t.k] + inorder(t.r) if t else []
root = None
for k in [8, 3, 10, 1, 6, 14]:
root = ins(root, k)
print(inorder(root)[2])Choose all true statements.
Which structure supports 'insert' and 'remove the largest' in O(log n)?
Practice on LeetCode
Union–Find, heaps / priority queues and binary search trees.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Redundant Connection ↗ | Medium | union–find: the edge whose ends are already joined | |
| Accounts Merge ↗ | Medium | union–find over emails | |
| Satisfiability of Equality Equations ↗ | Medium | union then check | |
| Last Stone Weight ↗ | Easy | a max-heap | |
| Kth Largest Element in a Stream ↗ | Easy | a min-heap of size k | |
| Top K Frequent Elements ↗ | Medium | counts plus a heap | |
| K Closest Points to Origin ↗ | Medium | heap of size k | |
| Merge k Sorted Lists ↗ | Hard | a heap of list heads: O(N log k) | |
| Find Median from Data Stream ↗ | Hard | two heaps | |
| Validate Binary Search Tree ↗ | Medium | the BST invariant (or in-order is increasing) | |
| Insert into a Binary Search Tree ↗ | Medium | BST insert | |
| Delete Node in a BST ↗ | Medium | the three deletion cases | |
| Kth Smallest Element in a BST ↗ | Medium | in-order traversal | |
| Lowest Common Ancestor of a Binary Search Tree ↗ | Medium | walk down using key order |
Key takeaways
- Union–Find supports
findandunion; with union-by-size and path compression, operations are almost O(1). - A priority queue serves the highest-priority item; a binary heap implements insert and delete in O(log n), stored in a plain array with children at 2i+1 and 2i+2.
heapifybuilds a heap in O(n); heap sort is O(n log n) in place.- A BST gives search/insert/delete in O(height); in-order traversal lists keys in sorted order; an unlucky insertion order makes height n.