Part 17 / Topic 17 of 20
Topological sort and union-find
Two graph tools for questions that BFS and DFS answer awkwardly. Topological sort orders a DIRECTED graph so every edge points forward โ "take Python basics before OOP" โ and exists exactly when there is no cycle. Union-find (disjoint set union) answers "are these two in the same group?" and "how many groups?" after merging many connections, without ever walking the graph. Think of planning a degree: topological sort is working out a semester order that respects every prerequisite; union-find is noticing that two students are in the same friend circle because friendships chain them together.
| Tool | Question it answers | Time |
|---|---|---|
| topological sort (Kahn's) | a valid order under prerequisites; detects cycles | O(V + E) |
| union-find | same group? how many groups? | near-O(1) per union/find (with path compression) |
Kahn's algorithm: repeatedly take something with no unfinished prerequisites. Anything left over at the end is stuck in a cycle:
print(course_order({
"Python basics": [],
"OOP": ["Python basics"],
"Testing": ["Python basics"],
"Web APIs": ["OOP", "Testing"],
"DSA": ["OOP"],
}))
# ['Python basics', 'OOP', 'Testing', 'DSA', 'Web APIs']
print(course_order({"A": ["B"], "B": ["C"], "C": ["A"]})) # None - a cycle
Union-find keeps a parent pointer per item; find walks to the group's root (compressing the path as it goes), union links two roots:
uf = UnionFind(["Ravi", "Asha", "Imran", "Kavya", "Meera"])
for a, b in [("Ravi", "Asha"), ("Asha", "Imran"), ("Kavya", "Meera")]:
uf.union(a, b)
print(uf.find("Ravi") == uf.find("Imran")) # True - chained through Asha
print(uf.find("Ravi") == uf.find("Kavya")) # False - separate circles
Real-world example: a build system (or this course's own stage order) is a topological sort of tasks; "merge duplicate customer accounts that share an email or phone" is union-find โ each shared detail is a union, and the final groups are the real customers.
โ ๏ธ Cycle detection differs by direction: in a directed graph, Kahn's leftover nodes (or a "currently visiting" marker in DFS) reveal the cycle; in an undirected graph, seeing an already-visited node that is not your immediate parent does. Using the undirected test on a directed graph reports cycles that are not there.
Practice: course-schedule style "is this order possible, and give one"; counting groups after merges (friend circles, connected accounts); union-find on grid or string-similarity groupings.
Practice on LeetCode - start here: Course Schedule ยท Course Schedule II
Show the full practice list (10 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Number of Provinces | Medium |
| Redundant Connection | Medium |
| Accounts Merge | Medium |
| Find Eventual Safe States | Medium |
| Satisfiability of Equality Equations | Medium |
| Smallest String With Swaps | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Minimum Height Trees | Medium |
| Evaluate Division | Medium |
| Most Stones Removed with Same Row or Column | Medium |
| Similar String Groups | Hard |
Full program: examples/17_toposort_union_find.py.
Exercise 17: Topological sort โ a valid cooking order
Scenario: A recipe lists steps and their prerequisites; you need any order that never starts a step before its prerequisites are done โ and to notice when the prerequisites loop.
What to do: Write build_order(prereqs) using Kahn's algorithm (a deque of zero-blocker steps; pull sorted names so the output is predictable, decrement each unlocked step's blocker count, append when it hits zero). If some steps never become ready, the graph has a cycle: return None. Print the order for the recipe below and for {"a": ["b"], "b": ["a"]}.
Starting data:
STEPS = {
"knead dough": ["mix flour"],
"mix flour": [],
"boil water": [],
"make tea": ["boil water"],
"roll roti": ["knead dough"],
"cook roti": ["roll roti"],
}
Sample output:
Order: ['boil water', 'mix flour', 'make tea', 'knead dough', 'roll roti', 'cook roti']
Cyclic recipe: None
Show the solution to Exercise 17
"""Exercise 17: Topological sort - a valid build order for recipes.
Kahn's algorithm: start from steps with no pending prerequisites and
unlock the rest as their blockers finish. A leftover step means the
prerequisites loop - no valid order, so return None.
Run: python ex17.py (macOS/Linux: python3 ex17.py)
"""
from collections import deque
STEPS = {
"knead dough": ["mix flour"],
"mix flour": [],
"boil water": [],
"make tea": ["boil water"],
"roll roti": ["knead dough"],
"cook roti": ["roll roti"],
}
CYCLIC = {"a": ["b"], "b": ["a"]}
def build_order(prereqs: dict[str, list[str]]) -> list[str] | None:
steps = set(prereqs) | {p for needs in prereqs.values() for p in needs}
blockers = {step: len(prereqs.get(step, [])) for step in steps}
unlocks: dict[str, list[str]] = {step: [] for step in steps}
for step, needs in prereqs.items():
for p in needs:
unlocks[p].append(step)
ready = deque(sorted(s for s, n in blockers.items() if n == 0))
order = []
while ready:
step = ready.popleft()
order.append(step)
for unlocked in sorted(unlocks[step]):
blockers[unlocked] -= 1
if blockers[unlocked] == 0:
ready.append(unlocked)
return order if len(order) == len(steps) else None
def main() -> None:
print(f"Order: {build_order(STEPS)}")
print(f"Cyclic recipe: {build_order(CYCLIC)}")
if __name__ == "__main__":
main()