Skip to problem
←

Topological Sort

Medium 0 attempts

Given a directed acyclic graph (DAG) with vertices labeled 0 through V - 1, return a topological ordering.

The adjacency list adj[u] contains destinations v of edges u → v. Every such edge requires u to appear before v in your result.

Include every vertex exactly once, including isolated vertices and vertices in disconnected components. Any order satisfying all edges is accepted; the result does not have to be numerically sorted or lexicographically smallest. The input is guaranteed to have no directed cycles.

Function contract

Implement topologicalSort(V, adj).

Output: Return an array containing every vertex exactly once, with u before v for each edge u → v. Any valid order is accepted.

Example 1

Input
V = 4
adj = [[],[0],[0],[0]]
Output
[1,2,3,0]

Explanation: Vertices 1, 2, and 3 must all precede 0. Their relative order is unrestricted, so [3,1,2,0] is also valid.

Example 2

Input
V = 1
adj = [[]]
Output
[0]
Constraints
  • 1 <= V <= 10^4
  • The adjacency list describes a directed acyclic graph on vertices 0 through V-1.
  • adj.length == V; adj[u] lists destinations of edges leaving u

Kahn's Algorithm (BFS)

Count incoming edges for each vertex. A zero-indegree vertex has no remaining prerequisites, so it can be emitted next. Remove its outgoing edges conceptually by decrementing its neighbors' indegrees, enqueuing each neighbor when that count becomes zero. Seed the queue with every zero-indegree vertex to include disconnected components. The DAG guarantee ensures all V vertices are eventually emitted.

javascript
function topologicalSort(V, adj) {
  const inDeg = Array(V).fill(0);
  for (let u=0;u<V;u++) for (const v of adj[u]) inDeg[v]++;
  const q = [], result = [];
  for (let i=0;i<V;i++) if (inDeg[i]===0) q.push(i);
  let head = 0;
  while (head < q.length) {
    const u = q[head++]; result.push(u);
    for (const v of adj[u]) if (--inDeg[v]===0) q.push(v);
  }
  return result;
}

Time: O(V + E) | Space: O(V)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript