Topological Sort (Kahn's Algorithm)

medium

Given a directed acyclic graph (DAG) with V vertices (0 .. V-1) and directed edges edges (each [u, v] means u must come before v), return a topological ordering — a linear order where every edge points forward. If several are valid, return the lexicographically smallest one.

Hints

A vertex is ready to place when its in-degree drops to 0.
Output ready vertices and decrement their successors' in-degrees (Kahn's algorithm).
To get the lexicographically smallest order, always take the smallest ready vertex — use a min-heap.

Common doubts

At each step several vertices may be ready; choosing the smallest label greedily produces the unique lexicographically smallest valid order.
If fewer than V vertices are output, some never reached in-degree 0 — they're stuck in a cycle.
Yes (reverse of finish times), but it doesn't naturally give the lexicographically smallest order without extra care.

Interview follow-ups

Courses are vertices, prerequisites are edges; a valid order exists iff the graph is a DAG.
Use a max-heap instead of a min-heap.

Fun facts

  • Kahn published this in 1962; it's the BFS counterpart to DFS finish-time ordering.
  • The in-degree-0 frontier is exactly the set of tasks with no remaining prerequisites.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: V = 4, edges = [[0,1],[0,2],[1,3],[2,3]]
Output: [0, 1, 2, 3]
0 first; then 1 before 2 (smaller); then 3.
Example 2
Input: V = 3, edges = [[2,0],[2,1]]
Output: [2, 0, 1]
2 must precede both 0 and 1; then 0 before 1.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - the graph is a DAG (no cycle) - edges are directed u -> v

Solve this problem →