Intermediate · Module 17 · Lesson 6

Topological sort

Order DAG nodes using indegrees or DFS finish times.

15–25 min readLesson 100 of 123 Interactive Lab

Lesson 100 of 123

1d streak

Interactive Visualization

Trace the algorithm state by state

Change the inputs, run an operation, and connect each visible state change to the explanation below.

Interactive algorithm lab

Kahn’s Topological Sort

Remove prerequisites using indegrees

Step 1 / 13

Current

—

Ready queue

A B

Output

—

Completed

0/6

Ain=0Bin=0Cin=2Din=1Ein=1Fin=2

Why this step happens

A and B have no remaining prerequisites, so they enter the queue.

Invariant to protect

Only nodes whose prerequisites are already output may enter the queue.

Topological Sort: Kahn’s BFS Algorithm & Cycle Detection

A topological sort of a Directed Acyclic Graph (DAG) linearly orders vertices such that for every directed edge u -> v, u appears before v. Kahn’s algorithm maintains in-degrees for all nodes: nodes with in-degree 0 are processed via a queue, decrementing neighbor in-degrees.

CourseSchedule.java
public boolean canFinish(int numCourses, int[][] prerequisites) {
    int[] inDegree = new int[numCourses];
    Map<Integer, List<Integer>> adj = new HashMap<>();

    for (int[] edge : prerequisites) {
        adj.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]);
        inDegree[edge[0]]++;
    }

    Queue<Integer> queue = new LinkedList<>();
    for (int i = 0; i < numCourses; i++) {
        if (inDegree[i] == 0) queue.offer(i);
    }

    int processed = 0;
    while (!queue.isEmpty()) {
        int course = queue.poll();
        processed++;
        for (int next : adj.getOrDefault(course, List.of())) {
            if (--inDegree[next] == 0) queue.offer(next);
        }
    }
    return processed == numCourses; // If processed < numCourses, a cycle exists!
}

Active Recall Checkpoint

How does Kahn’s algorithm detect cycles in a directed graph?

Show answer & explanation

Nodes involved in a directed cycle never reach an in-degree of 0, so they never enter the queue. If total processed nodes < V, the graph contains a cycle.

Use it when

Use topological sort for task scheduling, build dependencies (Make/Maven), course prerequisites, and package manager dependency resolution.

Reconsider when

Reconsider when the graph contains undirected edges or when cycles are known to be valid components.

Cost Model

Complexity & Trade-offs

Graph processing
O(V + E)
O(V)
Assumes adjacency-list representation unless stated otherwise.

When to use it

  • Networks, dependencies, connectivity, shortest paths, and grid movement.
  • Ordering prerequisite-constrained work.
  • Grouping reachable or mutually reachable states.

Common mistakes

  • Marking visited too late and enqueuing the same vertex repeatedly.
  • Ignoring disconnected components.
  • Using an algorithm whose weight assumptions do not match the graph.

Practice prompts

  • Reproduce the worked Topological sort example without looking at the trace.
  • Change one input condition and explain whether the Topological sort invariant still holds.
  • Implement the approach, derive its cost, and compare it with a straightforward baseline.

Mastery check

Can you derive it instead of memorizing it?

State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.