Question Bank

Topological Sort Essentials

Difficulty: Medium

Kahn's algorithm, DFS-based ordering, and using topo sort to detect cycles in directed graphs. Code stems are mostly Python.

Question Bank
/

Topological Sort Essentials

Topological Sort Essentials

Kahn's algorithm, DFS-based ordering, and using topo sort to detect cycles in directed graphs. Code stems are mostly Python.

Question Bank
Medium
Python
5 questions
topological-sort
graphs
algorithms
quiz

406 views

12

Implement Kahn's algorithm to return one valid topological order of the DAG given as an adjacency list. Return None if the graph has a cycle.

Examples

Example 1:

Input: n = 4, adj = [[1, 2], [3], [3], []]
Output: [0, 1, 2, 3]
Explanation: Compute in-degrees, seed a queue with zero-indegree vertices, then repeatedly pop and decrement neighbors. Each time a neighbor reaches indegree 0, push it. O(V + E).

Example 2:

Input: n = 2, adj = [[1], [0]]
Output: None
Explanation: The two vertices form a cycle. Neither ever reaches indegree 0, so the order has fewer than n vertices and Kahn returns None.