Simple chain
Input
n = 4, edges = [(0,1), (1,2), (2,3)]
Output
[0, 1, 2, 3]
Each node depends on the previous, so the only valid ordering is [0,1,2,3].
Full lesson preview
Implement Kahn's algorithm to produce a valid topological ordering of a directed acyclic graph (DAG). If the graph has a cycle, return an empty list.
Problem statement
Task
Examples
Input
n = 4, edges = [(0,1), (1,2), (2,3)]
Output
[0, 1, 2, 3]
Each node depends on the previous, so the only valid ordering is [0,1,2,3].
Input format
Output format
Constraints
Samples
Input
n = 6, edges = [(5,2), (5,0), (4,0), (4,1), (2,3), (3,1)]
Output
[4, 5, 0, 2, 3, 1]
Kahn's algorithm picking smallest available node first yields the deterministic order [4,5,0,2,3,1].