Topological sort of a task-dependency DAG
viaGlassdoor
Problem Given a directed acyclic graph (DAG) of task dependencies, return a valid execution order (topological sort) in which every task appears after all the tasks it depends on.
Input / Output
- Input:
ntasks (0..n-1) and a list of directed edges[a, b]meaning taskamust run before taskb. - Output: any valid topological ordering of all
ntasks, or an indication that none exists (the graph has a cycle).
Constraints
- 1 ≤ n ≤ 1e5, edges up to ~2e5.
- Must run in linear time; the graph may be disconnected.
Example
- n = 4, edges = [[0,1],[0,2],[1,3],[2,3]] →
[0, 1, 2, 3](or[0, 2, 1, 3]). - edges = [[0,1],[1,0]] → no valid order (cycle).
Expected approach
- Kahn's algorithm: compute in-degrees, repeatedly pop a 0-in-degree node, decrement neighbours; if fewer than
nnodes are emitted, a cycle exists. - DFS alternative: post-order push onto a stack, using a visiting/visited colour scheme for cycle detection.
- Time O(V + E), space O(V + E).
asked …