Course schedule: detect cycles and produce a topological order.
Problem
There are n courses and prerequisite pairs [a, b] meaning b must be taken before a. Return a valid order to take all courses, or report that it is impossible (a cycle). Real-world equivalents: build systems, task schedulers, Spring bean dependency ordering, database migration ordering.
Approach: Kahn's algorithm (BFS topological sort)
Build an adjacency list and an in-degree count. Start with all nodes of in-degree 0; repeatedly remove one, append it to the order and decrement its neighbours' in-degrees, enqueuing those that reach 0. If the order contains fewer than n nodes, the remaining nodes are in a cycle.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
class CourseSchedule {
static int[] order(int n, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
int[] inDegree = new int[n];
for (int[] p : prerequisites) {
graph.get(p[1]).add(p[0]); // edge: prerequisite -> course
inDegree[p[0]]++;
}
Deque<Integer> ready = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (inDegree[i] == 0) ready.offer(i);
int[] order = new int[n];
int idx = 0;
while (!ready.isEmpty()) {
int course = ready.poll();
order[idx++] = course;
for (int next : graph.get(course)) if (--inDegree[next] == 0) ready.offer(next);
}
return idx == n ? order : new int[0]; // empty array: there is a cycle
}
public static void main(String[] args) {
System.out.println(Arrays.toString(order(4, new int[][] {{1, 0}, {2, 0}, {3, 1}, {3, 2}}))); // [0, 1, 2, 3]
System.out.println(Arrays.toString(order(2, new int[][] {{1, 0}, {0, 1}}))); // [] (cycle)
}
}Complexity
O(V + E) time and space.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you detect a cycle with DFS instead?
Colour nodes WHITE (unvisited), GRAY (on the current recursion stack) and BLACK (finished). Visiting a GRAY neighbour means a back edge, hence a cycle. Adding nodes to a list when they turn BLACK and reversing it gives a topological order. Kahn's algorithm is iterative (no deep recursion) and naturally reports which nodes are stuck in cycles.
How would you compute the minimum number of semesters if independent courses can be taken in parallel?
Run Kahn's algorithm level by level: all nodes with in-degree 0 form the first semester, the nodes freed by them the second, and so on. The number of levels is the answer (the longest path in the DAG). The same idea schedules build or deployment steps in parallel waves.