Topological sort of a task-dependency DAG

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: n tasks (0..n-1) and a list of directed edges [a, b] meaning task a must run before task b.
  • Output: any valid topological ordering of all n tasks, 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).
asked …
LeaderboardSalaryAccount