PDSA Interactive Book
Week 6

Union-Find, Priority Queue, Heap, BST

Three structures that make 'merge groups', 'serve the biggest first' and 'keep things sorted' fast.

After this chapter you can…
  • 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:

OperationMeaning
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:

TrickWhat it does
Union by size/rankhang the smaller tree under the larger root, so trees stay shallow (height ≤ log n)
Path compressionafter finding the root, point every node on the path directly at it
Python · editable
Expected output: True False [0, 4, 6, 7]
Union–Find — merge components and watch the forestInteractive
How fast?

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.

Predict the output

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)}))
Check yourself

Why does union by size keep trees shallow?

Check yourself

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()).

Implementationinsertdelete_max
unsorted listO(1)O(n)
sorted listO(n)O(1)
heapO(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:

RelationIndex
children of node i2i + 1 and 2i + 2
parent of node i(i − 1) // 2
height of a heap of n nodes⌊log₂ n⌋
Max-heap — insert values and delete the maximumInteractive

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.

Python · editable
Expected output: [14, 9, 5, 3, 7, 2] 14 [9, 7, 5, 3, 2]
Predict the output

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.

Heap sort — build the heap, then extract maximaInteractive
Python · editable
Expected output: [1, 4, 2, 9, 8, 7, 6] [1, 2, 4, 6, 7, 8, 9] 9
Check yourself

Where in a max-heap stored as an array is the smallest element?

Check yourself

In the array [20, 15, 18, 7, 9, 10] (a max-heap), what is the parent of the value at index 5?

Check yourself

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.

Python · editable
Expected output: [20, 30, 40, 50, 60, 70, 80] True False 3
BST — insert, search, deleteInteractive
In-order traversal

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 deleteWhat to do
a leafjust remove it
one childreplace the node by that child
two childrenreplace 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.

Predict the output

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))
Check yourself

In a BST, where is the minimum key?

Check yourself

The in-order successor of node 50 in the tree built from [50, 30, 70, 60, 80] is…

Check yourself

The height of a BST with n nodes can be as large as…

Chapter challenge — Week 6

…
Check yourself

Which pair of operations gives Kruskal's algorithm its cycle test?

Predict the output

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)
Put in order

Insert a value into a max-heap.

Check yourself

A heap is stored in an array. Node at index 7: what is its parent's index?

Check yourself

Building a heap from n unsorted values by sift-down from the last parent costs…

Predict the output

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])
Check yourself

Choose all true statements.

Check yourself

Which structure supports 'insert' and 'remove the largest' in O(log n)?

Practice on LeetCode

Union–Find, heaps / priority queues and binary search trees.

How to practise

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.

0 / 14 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Redundant Connection ↗Mediumunion–find: the edge whose ends are already joined
Accounts Merge ↗Mediumunion–find over emails
Satisfiability of Equality Equations ↗Mediumunion then check
Last Stone Weight ↗Easya max-heap
Kth Largest Element in a Stream ↗Easya min-heap of size k
Top K Frequent Elements ↗Mediumcounts plus a heap
K Closest Points to Origin ↗Mediumheap of size k
Merge k Sorted Lists ↗Harda heap of list heads: O(N log k)
Find Median from Data Stream ↗Hardtwo heaps
Validate Binary Search Tree ↗Mediumthe BST invariant (or in-order is increasing)
Insert into a Binary Search Tree ↗MediumBST insert
Delete Node in a BST ↗Mediumthe three deletion cases
Kth Smallest Element in a BST ↗Mediumin-order traversal
Lowest Common Ancestor of a Binary Search Tree ↗Mediumwalk down using key order

Key takeaways

  • Union–Find supports find and union; 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.
  • heapify builds 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.

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.