Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs/Topological Sort

Learn the pattern · ~15 min

Topological Sort

also called Kahn's algorithm, DFS postorder, DAG ordering

Repeatedly take any task with nothing left to wait for, and let it free the tasks waiting on it. If you ever get stuck with tasks left, there's a cycle.

Signalsprerequisites / dependencies / build orderdetect a cycle in a directed graphDP over a DAGLearn firstGraph BFS / DFS
Cheat sheet and practice

Reach for it when you read

  • +Tasks with prerequisites or dependencies: "b must come before a", build order, course order.
  • +"Can all of them be finished?": an order exists exactly when the directed graph has no cycle.
  • +Rules about which item comes first, read off from comparisons (alien dictionary, sequence reconstruction).
  • +A DP on a directed graph with no cycles: longest path, earliest finish time, number of paths.

Not this one when

  • ×Undirected graph, "are these connected?": BFS/DFS or union-find; order means nothing there.
  • ×Shortest path with weights in a graph that may have cycles: Dijkstra or Bellman-Ford.
  • ×Sort by one key (deadline, start time): a plain sort or a greedy, no graph needed.

Learn Topological Sort

First, what is a "topological order"?

Three courses with arrows: 0 → 1 means "take 0 before 1".

012

The only order that respects every arrow is 0, 1, 2. That's a topological order: a list of the nodes of a directed graph (edges with arrows) where every arrow u → v has u somewhere before v.

Two facts first:

  • It only exists when there's no cycle. Add 2 → 0 and you'd need 0 before 1, 1 before 2 and 2 before 0. Impossible.
  • There's often more than one. With 0 → 1 and 0 → 2 only, both 0, 1, 2 and 0, 2, 1 work.

A directed graph with no cycle is a DAG (directed acyclic graph). Topological sort: find one valid order, or report a cycle.

How do we peel off an order?

Here's the graph we'll use all the way through: six courses.

012345
edges: 0→1, 0→2, 1→3, 2→3, 3→4, 5→4

For each node, count the arrows coming into it. That count is its indegree: how many courses it still waits for. Here indeg = [0, 1, 1, 2, 2, 0]. Course 3 waits for 1 and 2; course 4 waits for 3 and 5.

The rule is one line:

Take any node whose count is 0 (it waits for nothing), write it down, and lower the count of every node it points to.

step what happens indeg after order so far
1 0 and 5 are at 0. Take 0: 1 and 2 drop to 0 0 0 0 2 2 0 0
2 take 1: 3 drops from 2 to 1 0 0 0 1 2 0 0, 1
3 take 2: 3 drops to 0, it's free now 0 0 0 0 2 0 0, 1, 2
4 take 3: 4 drops to 1, still waiting for 5 0 0 0 0 1 0 0, 1, 2, 3
5 take 5: 4 drops to 0 0 0 0 0 0 0 0, 1, 2, 3, 5
6 take 4: it points to nothing 0 0 0 0 0 0 0, 1, 2, 3, 5, 4

Check every arrow against 0, 1, 2, 3, 5, 4: each one points forward. A node only reaches 0 after everything it waits for has been written down, so it can't be early.

The code for it

First build the graph and the counts. LeetCode gives pairs [a, b] meaning "to take a you must first take b", so the arrow goes b → a:

C++
vector<vector<int>> adj(n);
vector<int> indeg(n, 0);
for (auto& p : prerequisites) {
    adj[p[1]].push_back(p[0]);     // [a, b] means b → a: take b first
    indeg[p[0]]++;                 // a waits for one more course
}

You don't need to memorise this. One loop over the pairs: draw the arrow, add one to the count of the node it points at.

Why count arrows coming in, not going out? Because "in" means "what am I waiting for". Course 0 has two arrows out but none in, so it goes first. Course 4 has none out but two in, so it waits.

Fine, but how does this help us?

That's exactly Course Schedule II: n = 6, prerequisites = [[1,0],[2,0],[3,1],[3,2],[4,3],[4,5]], the graph above. Return any order that takes every course, or [] if none exists.

By hand we already found 0, 1, 2, 3, 5, 4. When is the answer []? Add [0,4] (take 4 before 0). Now 0 → 1 → 3 → 4 → 0 is a circle: each course on it waits for the one before it, so none of them ever reaches count 0. Only 5 can be taken, and the answer is [].

The brute force

Turn the hand rule into code: each round, scan all courses for one that's not placed and has count 0, place it, lower its targets.

C++
vector<bool> placed(n, false);
for (int round = 0; round < n; round++) {
    int pick = -1;
    for (int c = 0; c < n; c++)              // rescan every course
        if (!placed[c] && indeg[c] == 0) { pick = c; break; }
    if (pick == -1) return {};               // everyone left is waiting: a cycle
    placed[pick] = true;
    order.push_back(pick);
    for (int v : adj[pick]) indeg[v]--;
}

It's correct, but there are n rounds and each scans up to n courses. LeetCode caps n at 2,000, so it passes there. But take a chain of 10⁵ courses numbered backwards, n−1 → n−2 → … → 0 (CSES Course Schedule allows that): every scan walks almost to the end to find the one free course. About n²/2 = 5 × 10⁹ checks, about 1.5 seconds at -O2 against a 1-second limit. Time limit exceeded.

The one thought that fixes it

Stop right after step 1: we took 0, and 1 and 2 dropped to 0. Which courses could possibly have become free?

  • A count only changes when a course it waits for is taken.
  • Taking 0 lowered only 1 and 2, the nodes 0 points to. Courses 3 and 4 are still at 2: if they weren't free before, they aren't now.

So rescanning everybody is wasted work. The only courses that can become free are the targets of the one you just took, and you notice the moment their count hits 0. Put them in a queue right then.

That's the peel from step 2 with the scan replaced by a queue. It's called Kahn's algorithm. Seed the queue with every course at 0 (there may be several, the graph may be in pieces), and if fewer than n come out, the rest sit on a cycle.

C++
vector<int> findOrder(int n, vector<vector<int>>& prerequisites) {
    vector<vector<int>> adj(n);
    vector<int> indeg(n, 0), order;
    for (auto& p : prerequisites) {
        adj[p[1]].push_back(p[0]);
        indeg[p[0]]++;
    }
    queue<int> q;
    for (int i = 0; i < n; i++)
        if (indeg[i] == 0) q.push(i);           // waits for nothing
    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);     // only u's targets can become ready
    }
    if ((int)order.size() < n) return {};       // the rest sit on a cycle
    return order;
}

Dry run

Start: indeg = [0, 1, 1, 2, 2, 0], queue 0, 5.

pop counts that drop queue after order
0 1: 1→0, 2: 1→0, both join 5, 1, 2 0
5 4: 2→1 1, 2 0, 5
1 3: 2→1 2 0, 5, 1
2 3: 1→0, joins 3 0, 5, 1, 2
3 4: 1→0, joins 4 0, 5, 1, 2, 3
4 none empty 0, 5, 1, 2, 3, 4

All 6 placed: [0, 5, 1, 2, 3, 4]. A different order from the brute force's, and just as valid: check the arrows. With [0,4] added, the queue starts as just 5, popping it drops 4 to 1, and nothing else ever joins: 1 < 6, so [], the same as the brute force.

Why it's O(V + E)

Count what happens to each node and each edge. A node enters the queue once (its count hits 0 once) and leaves once; then each of its arrows lowers one count, once. V pushes and pops plus E decrements: O(V + E) time and space.

From O(V²) down to O(V + E), by only looking at the nodes whose count just changed.

Only "can all be finished?" Count them

Course Schedule asks yes or no. Same loop, one changed line at the end:

C++
return (int)order.size() == n;

On our graph: true. With [0,4]: false.

Prefer recursion? DFS, children first, then me

Run DFS and write a node down only after everything it points to is finished, then reverse. A node finishes after all its descendants, so reversed, it comes before them.

C++
vector<int> state(n, 0), order;      // 0 new, 1 on the call stack, 2 finished
hasCycle = false;
function<void(int)> dfs = [&](int u) {
    state[u] = 1;
    for (int v : adj[u]) {
        if (state[v] == 1) hasCycle = true;  // an arrow back into the stack
        if (state[v] == 0) dfs(v);
    }
    state[u] = 2;
    order.push_back(u);              // children first, then me
};
for (int u = 0; u < n; u++)
    if (state[u] == 0) dfs(u);
reverse(order.begin(), order.end());

On our graph the finish order is 4, 3, 1, 2, 0, 5, reversed 5, 0, 2, 1, 3, 4, another valid order. The middle state, "on the call stack", catches cycles: with [0,4], DFS goes 0 → 1 → 3 → 4 and finds an arrow back to 0, still on the stack. A plain seen flag can't tell that from a finished node, like 3 when DFS reaches it again from 2.

Remember this

  • "Before / after", "depends on", "prerequisite", "build order" → topological sort. "Is it possible?" → the same, plus the cycle check.
  • Read the direction: in LeetCode's [a, b], b comes first, so the arrow is b → a.
  • Seed the queue with every node at count 0; the graph may be in pieces.
  • Fewer than n nodes placed means a cycle. In DFS, a cycle is an arrow to a node still on the stack.
  • Whenever a problem, however dressed up, asks for an order that respects "x before y" rules, it's this.

Practise it on Course Schedule, then Course Schedule II (return the order), Find Eventual Safe States (work backwards from the sinks), Minimum Height Trees (peel leaves instead of sources) and Alien Dictionary (build the arrows from comparisons first).

Below, watch Course Schedule II run line by line.

Watch it work, line by line

Course Schedule II ↗, n = 6, 4→0, 5→0, 4→1, 0→3, 1→3, 3→2 → [4, 5, 1, 0, 3, 2]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Are there directed "before" relations, and do I need an order that respects all of them (or to know that none exists)?

Reach for it when

  • +prerequisites / dependencies / build order
  • +detect a cycle in a directed graph
  • +DP over a DAG
  • +derive an order from comparisons (alien dictionary)
  • +V + E up to 2e5

It fails when

  • ×Graph is undirected (connectivity, cycles)use Union-find or plain DFS
  • ×You need shortest paths or distancesuse BFS / Dijkstra (topo order only helps DP on DAGs)
  • ×Graph has cycles that must be handled, not just reporteduse Condense SCCs first, then topo-sort the DAG
  • ×No dependency or direction at alluse You don't need an ordering

Looks like it, isn't (and the other way round)

  • Longest Increasing Path in a Matrix looks like Grid / Matrix DP, needs this pattern

    Moves go in four directions, so there is no row-major order; the strict increase makes a DAG for memo DFS / Kahn.

  • Minimum Height Trees looks like Tree DFS (Paths & Recursion), needs this pattern

    Trying every root is O(n2); peeling leaves (Kahn on degree 1) finds centres.

  • Parallel Courses II looks like Topological Sort, needs Bitmask DP

    Greedy picking of available courses per semester is wrong; n <= 15 invites DP over taken masks.

  • Count Ways to Build Rooms in an Ant Colony looks like Topological Sort, needs Combinatorics mod p (nCr, Catalan, stars and bars)

    Counting topological orders of a tree is n! / product of subtree sizes. No enumeration needed.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1When does a node go into the queue?Reveal

    When its in-degree reaches 0: every node that must come before it has already been placed.

  • 2How does Kahn's algorithm detect a cycle?Reveal

    Nodes on a cycle never reach in-degree 0, so at the end fewer than n nodes are in the order.

  • 3The problem wants the lexicographically smallest valid order. What changes?Reveal

    Use a min-heap instead of a queue, so the smallest ready node is always taken first.

Practice ladder

every problem →
  1. 1Course Schedulejust detect the cycleMedium
  2. 2Course Schedule IIthe hookMedium
  3. 3Find Eventual Safe Stateswork backwardsMedium
  4. 4Minimum Height Treespeel leavesMedium
  5. 5Longest Flight Routelongest path in a DAGMedium
  6. 6Alien Dictionarybuild the graph from comparisonsHard
  7. 7Longest Increasing Path in a MatrixDP in topo orderHard
  8. 8Sort Items by Groups Respecting Dependenciestwo levels of orderingHard

Finished Topological Sort? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Topological Sort

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial