Topological Sort & DAGs

Data Structures & Algorithms · Graph Algorithms · Advanced · 25 min

Put tasks in an order where every prerequisite comes first, and spot impossible (cyclic) plans, using Kahn's algorithm or DFS.

A to-do board where a sticky note may only move to "Done" once every arrow pointing into it has been crossed off.

The idea in everyday words

Getting dressed has rules: socks before shoes, trousers before a belt, a shirt before a tie. There are many correct orders (you can put on the watch whenever you like), but never shoes before socks. Topological sort finds one correct order. And if two items each needed the other one first, you would be stuck forever: that is a cycle, and no order exists.

Dependencies are arrows

Write every task as a dot (a node) and every rule "a must happen before b" as an arrow a → b.

  • Directed = the arrows have a direction. "Intro before DSA" is not the same as "DSA before Intro".
  • Acyclic = you can never follow arrows and come back to where you started.
  • A graph that is both is a DAG (Directed Acyclic Graph).

A topological order is a list of all the nodes where every arrow points forward (from left to right).

Courses Rule
Intro → DSA take Intro before DSA
Intro → Databases take Intro before Databases
DSA → Algorithms take DSA before Algorithms

Valid orders: Intro, DSA, Databases, Algorithms or Intro, Databases, DSA, Algorithms. Both keep every arrow pointing forward. There is usually more than one answer, which is why interview problems often ask for "any" order, or pin it down with a rule like "smallest first".

Kahn's algorithm: peel off whatever is ready

Think of each node's in-degree = the number of arrows pointing into it = how many prerequisites it is still waiting for.

  1. Count the in-degree of every node.
  2. Every node with in-degree 0 waits for nobody. Put them in a "ready" queue.
  3. Take a ready node, append it to the answer, and cross off its outgoing arrows: each neighbour's in-degree drops by 1.
  4. Any neighbour that drops to 0 is now ready. Repeat until the queue is empty.

Why it works: we only place a node after all its prerequisites are placed, so every arrow points forward. Each node and each arrow is handled once, so it is O(V + E) (V = nodes, E = edges).

from collections import deque

def kahn(n, edges):
    graph = [[] for _ in range(n)]
    indeg = [0] * n
    for a, b in edges:          # a must come before b
        graph[a].append(b)
        indeg[b] += 1
    q = deque(v for v in range(n) if indeg[v] == 0)
    order = []
    while q:
        v = q.popleft()
        order.append(v)
        for w in graph[v]:
            indeg[w] -= 1
            if indeg[w] == 0:
                q.append(w)
    return order

print(kahn(4, [(0, 1), (0, 2), (1, 3), (2, 3)]))

Want a unique answer, such as "the smallest available course first"? Swap the queue for a min-heap (heapq). That costs O(log V) per step, so O((V + E) log V) overall.

Cycle detection comes for free

What if the rules are impossible, like "A before B" and "B before A"?

Nodes on a cycle wait for each other. Their in-degree never reaches 0, so they never enter the queue. When the queue runs dry, the answer list is shorter than n.

Rule: if len(order) < n, there is a cycle. That one line answers LeetCode's Course Schedule ("can you finish all courses?").

def can_finish(n, edges):
    graph = [[] for _ in range(n)]
    indeg = [0] * n
    for a, b in edges:
        graph[a].append(b)
        indeg[b] += 1
    ready = [v for v in range(n) if indeg[v] == 0]
    placed = 0
    while ready:
        v = ready.pop()
        placed += 1
        for w in graph[v]:
            indeg[w] -= 1
            if indeg[w] == 0:
                ready.append(w)
    return placed == n

print(can_finish(3, [(0, 1), (1, 2)]))          # True
print(can_finish(3, [(0, 1), (1, 2), (2, 1)]))  # False: 1 and 2 wait for each other

Notice the "ready" container can be a stack here. If you only need some order (or just yes/no), the container does not matter.

The DFS version: finish times, reversed

Depth-first search gives a second way. Explore as deep as you can from a node. A node is finished when everything after it is finished. So if you write nodes down as they finish, every node appears after all the nodes that depend on it. Reverse that list and you have a topological order.

To catch cycles, give each node one of three colours:

  • white (0) = not visited yet
  • grey (1) = on the current DFS path, still in progress
  • black (2) = finished

Reaching a grey node means you walked in a circle back onto your own path: a cycle.

def topo_dfs(n, edges):
    graph = [[] for _ in range(n)]
    for a, b in edges:
        graph[a].append(b)
    color = [0] * n
    finished = []
    def dfs(v):
        color[v] = 1                    # in progress
        for w in graph[v]:
            if color[w] == 1:
                return False            # back onto our own path: cycle
            if color[w] == 0 and not dfs(w):
                return False
        color[v] = 2                    # done
        finished.append(v)
        return True
    for v in range(n):
        if color[v] == 0 and not dfs(v):
            return []
    return finished[::-1]

print(topo_dfs(4, [(0, 1), (0, 2), (1, 3), (2, 3)]))

A plain "visited" flag is not enough for cycle detection in directed graphs: you must know whether a node is still on the path (grey) or already done (black).

Kahn or DFS?

Kahn (BFS-style) DFS
Idea repeatedly remove a node with no prerequisites reverse post-order (finish times)
Cycle check len(order) < n reach a grey node
Control the tie-breaks easy: use a heap awkward
"Minimum number of semesters" process the queue level by level not natural
Risk none Python recursion limit (about 1000) on long chains
Time / space O(V + E) / O(V + E) O(V + E) / O(V + E)

Default in interviews: Kahn's algorithm. It is iterative, the cycle check is one line, and it extends naturally to "smallest order" or "fewest rounds".

Step by step

  1. Count in-degrees:

    Arrows: 4→2, 5→2, 5→0, 2→1, 0→1, 1→6, 0→3. In-degrees: node 0 has 1, node 1 has 2, node 2 has 2, nodes 3 and 6 have 1, nodes 4 and 5 have 0.

  2. Seed the heap:

    Nodes 4 and 5 wait for nobody. ready = {4, 5}.

  3. Take 4:

    Smallest ready is 4. order = [4]. Cross off 4→2: node 2 now waits for 1 more. ready = {5}.

  4. Take 5:

    order = [4, 5]. Cross off 5→2 (node 2 hits 0) and 5→0 (node 0 hits 0). ready = {0, 2}.

  5. Take 0, then 2:

    Take 0: 0→1 leaves node 1 at 1, 0→3 makes 3 ready. ready = {2, 3}. Take 2: 2→1 makes 1 ready. ready = {1, 3}.

  6. Take 1, 3, 6:

    Take 1: 1→6 makes 6 ready. Then take 3, then 6. The heap is empty.

  7. Check for a cycle:

    order = [4, 5, 0, 2, 1, 3, 6] has all 7 nodes, so there is no cycle and every arrow points forward.

Code example

import heapq

def topo_order(n, edges):
    graph = [[] for _ in range(n)]
    indeg = [0] * n
    for a, b in edges:              # a must come before b
        graph[a].append(b)
        indeg[b] += 1
    ready = [v for v in range(n) if indeg[v] == 0]
    heapq.heapify(ready)            # smallest ready node first
    order = []
    while ready:
        v = heapq.heappop(ready)
        order.append(v)
        for w in graph[v]:
            indeg[w] -= 1
            if indeg[w] == 0:
                heapq.heappush(ready, w)
    return order if len(order) == n else []

plan = [(4, 2), (5, 2), (5, 0), (2, 1), (0, 1), (1, 6), (0, 3)]
print("order:", topo_order(7, plan))
print("with a cycle:", topo_order(3, [(0, 1), (1, 2), (2, 1)]))

Complexity

  • Time: O(V + E) with a plain queue, every node and arrow is handled once; O((V + E) log V) with a min-heap for smallest-first
  • Space: O(V + E) for the adjacency list, in-degree array and queue

Interview tips

  • Say the arrow direction out loud before coding: "pair [a, b] means b before a, so the edge is b → a".

  • Mention both methods (Kahn and DFS) and pick Kahn for its one-line cycle check and easy tie-breaking.

  • Classic follow-ups: return the order (Course Schedule II), detect impossibility, alien dictionary, minimum semesters (BFS by levels).

  • State the complexity as O(V + E), and O((V + E) log V) if you use a heap for a specific order.

  • If you use recursive DFS in Python, mention the recursion limit and that Kahn avoids it.

Challenge: Course Order (smallest first)

There are n courses numbered 0 to n - 1. Each pair [course, pre] in prerequisites means you must take pre before course.

Return an order to take all courses. Whenever several courses are available, take the smallest number first (so the answer is unique). If it is impossible to finish (there is a cycle), return [].

Aim for O((V + E) log V): one test has a very long chain of courses, so rescanning every course each round is too slow.

Example: course_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]]) → [0, 1, 2, 3]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Graph Algorithms

Previous: Backtracking · Next: Shortest Paths (Dijkstra)