DSA Tracker

Problem

Medium

Topological Sort (Kahn's Algorithm)

A medium Graph interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Graph
Sheets
1
Core for
12 roles

The problem

Given a directed acyclic graph with numVertices vertices and a list of directed edges, return a topological ordering using Kahn's algorithm (BFS-based topological sort).

Example 1

Input
numVertices = 4, edges = [[3,0],[3,1],[2,1],[1,0]]
Output
[3,2,1,0]
Why
Vertex 3 has no incoming edges, then 2, then 1, then 0 in BFS topological order.

Example 2

Input
numVertices = 6, edges = [[5,0],[5,2],[4,0],[4,1],[2,3],[3,1]]
Output
[5,4,2,3,1,0]
Why
Process nodes with no incoming edges in BFS order.

Constraints

  • 1 <= numVertices <= 100
  • 0 <= edges.length <= numVertices * (numVertices - 1) / 2

How to think about it

Updated 2026-09-29

Every directed acyclic graph contains at least one node with in-degree 0. Enqueue these initial sources; popping a node outputs it next in the linear order. Decrementing the in-degrees of its targets simulates deleting the node and its outgoing arrows, continuously revealing the next tier of dependency-free vertices.

Approaches, worst first

  1. DFS post-order traversal stack

    time O(V + E) · space O(V + E)

    Traverse unvisited vertices with recursive depth-first search, appending each vertex to an ordering list only after all directed descendants finish. Reversing the completed post-order list yields a valid topological sequence, but requires recursion stack overhead and explicit cycle-state flags.

  2. In-degree array with queue BFSWrite this one

    time O(V + E) · space O(V + E)

    Compute in-degrees for all vertices from 0 to numVertices - 1. Enqueue those with in-degree 0. Dequeue u, append to ordering list, and for each outgoing edge `u -> v`, decrement in-degree of v. Whenever in-degree of v becomes 0, push v to the queue.

Where people lose marks · 3
  • If a cycle exists, the queue will empty before processing all vertices, resulting in an output array shorter than numVertices.
  • Multiple independent nodes can have in-degree 0 concurrently; any arbitrary tie-breaking order among them produces a valid topological sort.
  • Edges array can be empty, where any permutation of `[0, ..., numVertices - 1]` is a valid answer.

Full solution

C++
#include <bits/stdc++.h>
using namespace std;

vector<int> topoSort(int v, vector<vector<int>>& adj) {
    vector<vector<int>> graph(v);
    vector<int> indegree(v, 0);
    for (const auto& edge : adj) {
        int u = edge[0], w = edge[1];
        graph[u].push_back(w);
        indegree[w]++;
    }
    queue<int> q;
    for (int i = 0; i < v; i++) {
        if (indegree[i] == 0) q.push(i);
    }
    vector<int> order;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        order.push_back(u);
        for (int nxt : graph[u]) {
            if (--indegree[nxt] == 0) {
                q.push(nxt);
            }
        }
    }
    return (int)order.size() == v ? order : vector<int>{};
}
Java
import java.util.*;

public class Main {
    static int[] topoSort(int v, int[][] adj) {
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < v; i++) graph.add(new ArrayList<>());
        int[] indegree = new int[v];
        for (int[] edge : adj) {
            int u = edge[0], w = edge[1];
            graph.get(u).add(w);
            indegree[w]++;
        }
        Queue<Integer> q = new LinkedList<>();
        for (int i = 0; i < v; i++) {
            if (indegree[i] == 0) q.offer(i);
        }
        int[] order = new int[v];
        int idx = 0;
        while (!q.isEmpty()) {
            int u = q.poll();
            order[idx++] = u;
            for (int nxt : graph.get(u)) {
                if (--indegree[nxt] == 0) {
                    q.offer(nxt);
                }
            }
        }
        return idx == v ? order : new int[0];
    }
}
Python
# Reference for #324 Topological Sort (Kahn's Algorithm)
# topo_sort(v: int, adj: list[list[int]]) -> list[int]
from collections import deque

def topo_sort(v: int, adj: list[list[int]]) -> list[int]:
    graph = [[] for _ in range(v)]
    indegree = [0] * v
    for u, w in adj:
        graph[u].append(w)
        indegree[w] += 1

    queue = deque([i for i in range(v) if indegree[i] == 0])
    order = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for nxt in graph[u]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)

    return order if len(order) == v else []
JavaScript
// Reference for #324 Topological Sort (Kahn's Algorithm)
// topoSort(v: number, adj: number[][]): number[]

function topoSort(v, adj) {
  const graph = Array.from({ length: v }, () => []);
  const indegree = new Array(v).fill(0);
  for (const [u, w] of adj) {
    graph[u].push(w);
    indegree[w]++;
  }

  const queue = [];
  for (let i = 0; i < v; i++) {
    if (indegree[i] === 0) queue.push(i);
  }

  const order = [];
  while (queue.length > 0) {
    const u = queue.shift();
    order.push(u);
    for (const nxt of graph[u]) {
      indegree[nxt]--;
      if (indegree[nxt] === 0) queue.push(nxt);
    }
  }

  return order.length === v ? order : [];
}

module.exports = { topoSort };
Try it in the editor

The theory behind it

Graph — the ground this problem stands on. All Graph problems

What Graph is

A graph is a network of individual points, called vertices or nodes, connected by lines called edges. Think of a subway transit map, an electrical circuit, or a web of social friends. Unlike a tree, a graph has no designated top node and no parent-child hierarchy. Connections can run one-way or both ways, and paths can loop back on themselves to form closed cycles.

When to reach for it

Reach for graph algorithms when inputs describe relationships, networks, flights between cities, course prerequisites, or clone networks. Signals include finding the shortest route across unweighted connections, ordering tasks that depend on earlier tasks, counting isolated clusters, or checking whether a path contains an infinite loop. Whenever problems present pairs of related entities and ask for reachability, distances, or dependencies, graph representations apply.

How the pattern works

First convert edge lists into an adjacency list, mapping each node to an array of its neighbors. Choose your exploration strategy based on the goal: use a queue and breadth-first search to find the shortest path in unweighted networks, or use recursion and depth-first search to explore full paths and detect cycles. Because graphs can have loops, always track visited nodes in a set or boolean array. Add nodes to the visited set at the moment they enter the queue so they are never visited twice.

More Graph problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .