Graphs · Pattern 8 of 14
Topological sort: an order that respects every dependency
Count how many edges point into each node. Nodes with none can go first; removing them frees their neighbours. If some nodes never reach zero, there is a cycle and no valid order.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Tasks, courses or recipes with prerequisites
- Find any order that respects every "a before b" rule, or say none exists
- The longest chain, or the number of rounds when independent tasks run in parallel
- Peel a tree from its leaves inwards
The template
// Kahn's algorithm. Edge [u, v]: u must come before v. Empty result: there is a cycle.
int[] topoSort(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] e : edges) { adj.get(e[0]).add(e[1]); indeg[e[1]]++; }
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i); // nothing to wait for
int[] order = new int[n];
int k = 0;
while (!q.isEmpty()) {
int u = q.poll();
order[k++] = u;
for (int v : adj.get(u)) if (--indeg[v] == 0) q.offer(v); // v's last prerequisite is done
}
return k == n ? order : new int[0];
}
// peel leaves layer by layer: the last 1 or 2 nodes are the centres of the tree
int[] findMinHeightTrees(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] deg = new int[n];
for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); deg[e[0]]++; deg[e[1]]++; }
Deque<Integer> leaves = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (deg[i] <= 1) leaves.offer(i);
for (int left = n; left > 2; ) {
left -= leaves.size();
for (int size = leaves.size(); size > 0; size--) {
int u = leaves.poll();
for (int v : adj.get(u)) if (--deg[v] == 1) leaves.offer(v);
}
}
return leaves.stream().mapToInt(Integer::intValue).toArray();
} from collections import deque
def topo_sort(n, edges): # Kahn's algorithm; edge [u, v]: u before v
adj, indeg = [[] for _ in range(n)], [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0) # nothing to wait for
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: # v's last prerequisite is done
q.append(v)
return order if len(order) == n else [] # fewer than n: a cycle
def find_min_height_trees(n, edges): # peel leaves; the last 1 or 2 nodes are the centres
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
deg = [len(a) for a in adj]
leaves, left = [i for i in range(n) if deg[i] <= 1], n
while left > 2:
left -= len(leaves)
nxt = []
for u in leaves:
for v in adj[u]:
deg[v] -= 1
if deg[v] == 1:
nxt.append(v)
leaves = nxt
return leaves // Kahn's algorithm. Edge [u, v]: u must come before v. Empty result: there is a cycle.
vector<int> topoSort(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
vector<int> indeg(n, 0), order;
for (auto& e : edges) { adj[e[0]].push_back(e[1]); indeg[e[1]]++; }
queue<int> q;
for (int i = 0; i < n; i++) if (indeg[i] == 0) q.push(i); // nothing to wait for
while (!q.empty()) {
int u = q.front(); q.pop();
order.push_back(u);
for (int v : adj[u]) if (--indeg[v] == 0) q.push(v); // v's last prerequisite is done
}
if ((int)order.size() < n) order.clear();
return order;
}
// peel leaves layer by layer: the last 1 or 2 nodes are the centres of the tree
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
vector<int> deg(n, 0), leaves;
for (auto& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); deg[e[0]]++; deg[e[1]]++; }
for (int i = 0; i < n; i++) if (deg[i] <= 1) leaves.push_back(i);
for (int left = n; left > 2; ) {
left -= leaves.size();
vector<int> next;
for (int u : leaves)
for (int v : adj[u]) if (--deg[v] == 1) next.push_back(v);
leaves = next;
}
return leaves;
} // Kahn's algorithm. Edge [u, v]: u must come before v. Empty result: there is a cycle.
function topoSort(n, edges) {
const adj = Array.from({ length: n }, () => []), indeg = new Array(n).fill(0);
for (const [u, v] of edges) { adj[u].push(v); indeg[v]++; }
const order = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) order.push(i); // nothing to wait for
for (let head = 0; head < order.length; head++) // order doubles as the queue
for (const v of adj[order[head]]) if (--indeg[v] === 0) order.push(v);
return order.length === n ? order : [];
}
// peel leaves layer by layer: the last 1 or 2 nodes are the centres of the tree
function findMinHeightTrees(n, edges) {
const adj = Array.from({ length: n }, () => []);
for (const [u, v] of edges) { adj[u].push(v); adj[v].push(u); }
const deg = adj.map((a) => a.length);
let leaves = [];
for (let i = 0; i < n; i++) if (deg[i] <= 1) leaves.push(i);
for (let left = n; left > 2; ) {
left -= leaves.length;
const next = [];
for (const u of leaves) for (const v of adj[u]) if (--deg[v] === 1) next.push(v);
leaves = next;
}
return leaves;
} The variations
-
1Kahn's algorithm: order the tasks
Start with every node of in-degree 0. Each time you take one, lower its neighbours' in-degree and queue the ones that reach 0. "Can all courses finish?" is just "did all n nodes come out?".
Now you solve -
2Build the graph first
The edges are hidden in the input. Compare neighbouring words: the first letter where they differ gives one edge. A recipe depends on each of its ingredients; supplies are the starting nodes.
Now you solve -
3DP along the topological order
Process nodes in topological order and push a value to each neighbour: the earliest semester or finish time (longest path), or the quietest richer person. In a grid, "strictly increasing" makes the edges acyclic, so the longest increasing path is a DP over the same order.
Now you solve -
4Peel a tree from its leaves
The same in-degree idea on a tree: remove all leaves (degree 1), then the new leaves, layer by layer. The last 1 or 2 nodes are the centres. Coinless leaves can be trimmed the same way before trimming two more layers.
Now you solve
Mistakes to avoid
- Getting the edge direction backwards: for
[course, prereq]the edge goes prereq → course. - Returning the partial order when there is a cycle. Always check that every node made it into the order.
- Alien dictionary: when a word is followed by its own prefix (like "abc" before "ab"), the order is invalid. Also add every letter as a node, even ones with no edges.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.