Graphs Topological sort
458. Topological Sort (Kahn's Algorithm)
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
Input: n = 6
edges = [[2, 0],
[2, 5],
[0, 1],
[5, 1],
[1, 3],
[4, 3]]
[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
Input: n = 4, edges = [[3, 1]]
[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
Input: n = 4, edges = [[3, 2], [2, 1], [1, 0]]
[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.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 2 × 105edges[i].length == 20 ≤ ui, vi < nui ≠ vi- No edge appears twice.
- The graph has no cycles.
Clarifying questions
What you would ask an interviewer before writing any code.