← All Exercises
Topological Sort with Kahn's Algorithm
advancedpython
Background
Build systems and task schedulers need a valid ordering of prerequisites; Kahn's algorithm exposes cycles naturally because cyclic nodes never reach indegree zero.
Problem
Given n nodes labeled 0..n-1 and directed edges (before, after), return a topological order that always picks the smallest available node. Return None if the graph contains a cycle. Reject endpoints outside 0..n-1.
Input
Node count n and a list of directed (before, after) edges.
Output
A deterministic topological order as a list, or None when a cycle exists.
Sample tests
Sample 1
Input: n = 4, edges = [[1, 0], [2, 0], [3, 1], [3, 2]]
Expected: [3, 1, 2, 0]
Sample 2
Input: n = 2, edges = [[0, 1], [1, 0]]
Expected: None
Sample 3
Input: n = 3, edges = []
Expected: [0, 1, 2]
Your solution
Learning objective
Implement Kahn's algorithm with indegrees and a min-heap for deterministic ordering and cycle detection.