Skip to interview prep
Apexed

64. Topological Sort

MediumGraphs

Return an order of nodes 0 to n − 1 in which every edge [u, v] has u before v. When several nodes are available, take the smallest label first. Return [] if the graph has a cycle.

Example 1

Input: n = 4, edges = [[0, 1], [0, 2], [1, 3], [2, 3]]
Output: [0, 1, 2, 3]

Constraints

  • 1 ≤ n ≤ 1000

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 4 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Topological Sort — coding interview practice — Apexed