oneby7

Graphs Topological sort

458. Topological Sort (Kahn's Algorithm)

Medium

You are given a directed graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges is an edge from vertex u to vertex v. The graph has no cycles: if you follow edges from any vertex, you never come back to it.

Return a topological order of the graph. That is a list of all n vertices, each exactly once, in which u comes before v for every edge [u, v].

Often several orders work, and any of them is correct. The result shows a valid topological order when the order you return is one. Otherwise it shows the first thing wrong with it, such as vertex 7 appears twice or edge 3 → 5 goes backwards: 5 is at position 2, 3 at position 9. Positions count from 0.

Example 1

012345

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

Output: [2,4,0,5,1,3]

Explanation: No edge comes into vertex 2 or vertex 4, so either can go first. Vertex 1 must wait for 0 and 5, and vertex 3 must wait for 1 and 4. [4,2,5,0,1,3] is also correct.

Example 2

0123

Input: n = 4, edges = [[3, 1]]

Output: [0,2,3,1]

Explanation: The only edge puts 3 before 1. Vertices 0 and 2 have no edges at all, but they still belong in the order, anywhere in it.

Example 3

0123

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

Output: [3,2,1,0]

Explanation: The edges form one chain, 3 → 2 → 1 → 0, so this is the only correct order.

Check your understanding

Work out the answer for this input before you write any code.

n = 5, edges = [[0, 2], [1, 2], [2, 3]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 2 × 105
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • ui ≠ vi
  • No edge appears twice.
  • The graph has no cycles.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.