Video in progress
You're given courses and their prerequisites. How do you determine whether all the courses can be taken, and in what order?
This is a directed graph, and the answer is a topological sort. Kahn's algorithm: I put the nodes with in-degree 0 into a queue and remove them one by one. If not every node comes out, the graph has a cycle and there's no valid order. O(V + E).
📖 Answer
"To take A you first need B" is an edge B → A. A topological order is a sequence in which, for every edge, the source comes first. It exists only in a graph without cycles (a DAG).
static List<Integer> order(int n, int[][] prereq) { // prereq[i] = {course, required_first}
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] p : prereq) {
g.get(p[1]).add(p[0]);
indeg[p[0]]++;
}
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i);
List<Integer> res = new ArrayList<>();
while (!q.isEmpty()) {
int v = q.poll();
res.add(v);
for (int u : g.get(v)) {
if (--indeg[u] == 0) q.offer(u);
}
}
return res.size() == n ? res : List.of(); // empty means there is a cycle
}
The alternative is DFS with three-color marking (white, gray, black). If you run into a gray node again, there's a cycle. When a node turns black you add it to the result, and at the end you reverse the list.
Where it shows up in practice: dependencies between Flyway migrations, module order in a build system, the order in which Spring beans are created, steps in a workflow. Spring's "circular dependency" error is exactly this cycle.
A convenient thing about Kahn's algorithm: it also shows you the nodes stuck in the cycle, the ones whose indeg stays above zero. It's easy to show the user "which courses are waiting on each other".
Sign up to mark studied questions and save your progress.