Topological sort or Kahn's algorithm
Pattern: Topological sort
Kahn's algorithm: count incoming edges; vertices with none are ready. Repeatedly take a ready vertex, output it, and remove its outgoing edges, which may make others ready. Taking the smallest ready vertex each time gives a single fixed order.
The problem
Given a directed acyclic graph, return a topological order: every edge [u, v] has u before v. Several orders can be valid; this guide always takes the smallest-numbered vertex that is ready, so the answer is unique.
Think first
- Which vertex can come first?
- What happens to the others when it is removed?
- How do you always pick the same order?
Hints
Brute force, and why it fails
Repeatedly scan all vertices for one with in-degree 0: O(V²).
The key insight
In-degrees tell you which vertices are free to go next, and each edge is removed once.
Dry run
| ready | 4 5 |
|---|
n = 6, edges 5 → 2, 5 → 0, 4 → 0, 4 → 1, 2 → 3, 3 → 1. Ready: 4 and 5.
The plan
indegree; ready = min-heap of in-degree 0
while ready: u = pop; output u; for v: indegree[v] -= 1; if 0: push v
Complexity
- Time
O((V + E) log V)- Space
O(V + E)
Heap operations for every vertex; a plain queue gives O(V + E) with any valid order.
Edge cases
- A single vertex with no edges.
- A graph in several pieces.
- A chain: one order only.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> topoSort(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] indegree = new int[n];
for (int[] e : edges) { adj.get(e[0]).add(e[1]); indegree[e[1]]++; }
PriorityQueue<Integer> ready = new PriorityQueue<>(); // vertices with nothing left before them, smallest first
for (int i = 0; i < n; i++) if (indegree[i] == 0) ready.add(i);
List<Integer> order = new ArrayList<>();
while (!ready.isEmpty()) {
int u = ready.poll();
order.add(u);
for (int v : adj.get(u)) if (--indegree[v] == 0) ready.add(v); // u is done: v may now be ready
}
return order;
}
}C++
class Solution {
public:
vector<int> topoSort(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
vector<int> indegree(n, 0);
for (const vector<int>& e : edges) { adj[e[0]].push_back(e[1]); indegree[e[1]]++; }
priority_queue<int, vector<int>, greater<int>> ready; // vertices with nothing left before them, smallest first
for (int i = 0; i < n; i++) if (indegree[i] == 0) ready.push(i);
vector<int> order;
while (!ready.empty()) {
int u = ready.top();
ready.pop();
order.push_back(u);
for (int v : adj[u]) if (--indegree[v] == 0) ready.push(v); // u is done: v may now be ready
}
return order;
}
};Python
import heapq
class Solution:
def topoSort(self, n: int, edges: list[list[int]]) -> list[int]:
adj, indegree = [[] for _ in range(n)], [0] * n
for e in edges:
adj[e[0]].append(e[1])
indegree[e[1]] += 1
ready = [i for i in range(n) if indegree[i] == 0] # nothing left before them, smallest first
heapq.heapify(ready)
order = []
while ready:
u = heapq.heappop(ready)
order.append(u)
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
heapq.heappush(ready, v) # u is done: v may now be ready
return orderCommon mistakes
- Starting from vertex 0 instead of the vertices with in-degree 0.
- Using DFS finishing order without reversing it.