← DiffPush

Topological Sort of a DAG

Standard Bar Graphs · Topo Sort Problems O(V + E) · O(V)

The Assembly-Line Sequencing Sheet

A factory's installation manual lists one-way dependency tickets between workstations: certain stations must finish before others may start. The planner needs one legal run order — any order where every ticket's predecessor comes first. With no loops guaranteed, a finish-time walk down the ticket map, read backwards, produces a valid sequence.

Input: An integer nodes and an edge list graph where each entry [u, v] is a one-way dependency u -> v. The graph is a DAG.

Output: Return a topological order — a permutation of 0..nodes-1 in which every edge u -> v has u appearing before v.

Constraints

Examples

Example 1

Input: {"nodes":4,"graph":[[0,1],[0,2],[1,3],[2,3]]}
Output: [0,2,1,3]
0 must precede 1 and 2, and both must precede 3 — this order satisfies every ticket.

Example 2

Input: {"nodes":3,"graph":[[2,0],[2,1]]}
Output: [2,1,0]
Station 2 has no predecessors and lands first; 0 and 1 are free afterwards.

Solve this in your browser →

Also on LeetCode ↗