Linear dependency ordering and cycle detection in Directed Acyclic Graphs (DAG)
39 problems·1 Easy·15 Medium·23 Hard
Pattern Study Guide & Cheat Sheet· O(V + E) linear scan of nodes and dependency edges · O(V + E) graph + queue
▼
Linearly order vertices in a Directed Acyclic Graph (DAG) such that for every directed edge u -> v, vertex u comes before v (Kahn's algorithm using indegree BFS).
Core Invariant: Kahn's Algorithm: Any node with `indegree == 0` has no remaining prerequisites and can be processed immediately. When processed, decrement indegrees of all outgoing neighbors; new 0-indegree nodes become eligible.
Recognize it (Keywords & Signals)
Task prerequisite scheduling / course schedule
Compilation dependency order
Build system build sequence
Detect cycle in directed graph
Alien dictionary (derive alphabet ordering)
When NOT to use
Undirected graphs (use standard BFS/DFS or DSU) or graphs known to contain self-loops/cycles where no order can exist.
How to solve (Step-by-step)
1.Build adjacency list `graph` and calculate `indegree` array/map for all nodes.
2.Enqueue all nodes with `indegree == 0` into a `queue`.
3.Initialize `order = []`.
4.While queue: pop `curr`, append to `order`. For each neighbor `nxt` of `curr`, decrement `indegree[nxt] -= 1`.
5.If `indegree[nxt] == 0`, enqueue `nxt`.
6.Cycle check: if `len(order) == num_nodes`, a valid topological order exists; otherwise, a directed cycle was present!
Watch for (Interview Traps)
Reversing edge directions (e.g. `[a, b]` direction is `b -> a`, not `a -> b`)
Failing to detect cycles by assuming all nodes are processed
Disconnected nodes: ensure all vertices `0..n-1` are registered in the indegree table
Kahn's Algorithm (BFS Indegree Topological Sort)
from collections import deque, defaultdict
def topological_sort(num_courses: int, prerequisites: list[list[int]]) -> list[int]:
graph = defaultdict(list)
indegrees = [0] * num_courses
# Prerequisite [a, b] means: must take b before a (edge: b -> a)
for course, prereq in prerequisites:
graph[prereq].append(course)
indegrees[course] += 1
# Start with all nodes having zero prerequisites
queue = deque([i for i in range(num_courses) if indegrees[i] == 0])
order = []
while queue:
curr = queue.popleft()
order.append(curr)
for next_course in graph[curr]:
indegrees[next_course] -= 1
if indegrees[next_course] == 0:
queue.append(next_course)
# If order doesn't include all courses, a cycle exists
return order if len(order) == num_courses else []
Cost
O(V + E) linear scan of nodes and dependency edges · O(V + E) graph + queue (Optimal linear time dependency resolution.)
Canonical problems
#207 Course Schedule:Detect if prerequisites form a cycle (len(order) == n)
#210 Course Schedule II:Return the actual linear order of courses
#269 Alien Dictionary:Derive character edge directions from adjacent words and sort
#310 Minimum Height Trees:Repeatedly trim leaves (degree 1) inward toward the center
What is the Topological Sort (Kahn's & DFS) pattern in coding interviews?
Linear dependency ordering and cycle detection in Directed Acyclic Graphs (DAG) It is categorized under Trees & Graphs and features 39 curated interview problems across Easy (1), Medium (15), and Hard (23) difficulties.
Which tech companies frequently test Topological Sort (Kahn's & DFS)?
How do I master the Topological Sort (Kahn's & DFS) pattern?
Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.