cswork / templatesOpen the Line 500 list

STOP 16 · GRAPHS

Topological Sorting and Dependencies

Kahn's algorithm: dequeue zero in-degree nodes O(V + E)

Contest ratings Rating 1693–Rating 1962· median Rating 1836(4 of 7 problems rated by zerotrac)

Open the Line 500 list · stop 16 · 7 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 9 companies · in 12 reportsUber 3, TikTok / ByteDance 2, Adobe 1, Meta 1, Netflix 1

Warm up with this one

LC 207Course ScheduleMedium
Stuck? Peek at the approach

Model prerequisites as a directed graph and detect cycles through topological sorting.

Key points

  1. A node with in-degree 0 has no unfinished prerequisites; place it, then decrement the in-degree of everything it points to.
  2. If fewer than n nodes come out, the rest sit on a cycle; that is the whole check for course-schedule problems.
  3. For the lexicographically smallest order, replace the queue with a min-heap.

Common pitfalls

  • Reading an edge backwards ("a depends on b" means b → a) reverses the whole order.
  • Enqueuing only the nodes that start at in-degree 0 and forgetting the ones that drop to 0 later.
  • A DFS topological sort with only visited/unvisited cannot see cycles; it needs a third "in progress" state.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Topological sort · Kahn’s algorithm

Order 6 courses so that every prerequisite comes first

Try your own input
ABCDEF
0in A
0in B
2in C
1in D
2in E
2in F
CurrentDiscovered / computedAnswer
Front → back
AB
Order
—

An arrow X → Y means X must come before Y. A, B have in-degree 0, so they join the queue first.

InvariantThe queue only holds nodes with in-degree 0: their prerequisites are out, so outputting them breaks no edge.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 207, with it.

Python
from collections import deque


def topo_order(n: int, edges: list[tuple[int, int]]) -> list[int]:
    """Edge (u, v) means u comes before v. Returns [] if there is a cycle."""
    graph = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:
        graph[u].append(v)
        indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in graph[u]:
            indeg[v] -= 1
            if indeg[v] == 0:  # every prerequisite of v is placed
                q.append(v)
    return order if len(order) == n else []
C++
// Edge {u, v} means u comes before v. Returns {} if there is a cycle.
vector<int> topoOrder(int n, const vector<pair<int, int>>& edges) {
    vector<vector<int>> graph(n);
    vector<int> indeg(n, 0);
    for (auto [u, v] : edges) {
        graph[u].push_back(v);
        indeg[v]++;
    }
    queue<int> q;
    for (int i = 0; i < n; i++)
        if (indeg[i] == 0) q.push(i);
    vector<int> order;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        order.push_back(u);
        for (int v : graph[u])
            if (--indeg[v] == 0) q.push(v);  // every prerequisite of v is placed
    }
    if ((int)order.size() < n) order.clear();
    return order;
}
Java
class Solution {
    // Edge {u, v} means u comes before v. Returns an empty list if there is a cycle.
    List<Integer> topoOrder(int n, int[][] edges) {
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
        int[] indeg = new int[n];
        for (int[] e : edges) {
            graph.get(e[0]).add(e[1]);
            indeg[e[1]]++;
        }
        Deque<Integer> q = new ArrayDeque<>();
        for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i);
        List<Integer> order = new ArrayList<>();
        while (!q.isEmpty()) {
            int u = q.poll();
            order.add(u);
            for (int v : graph.get(u))
                if (--indeg[v] == 0) q.offer(v); // every prerequisite of v is placed
        }
        return order.size() == n ? order : new ArrayList<>();
    }
}
Go
// topoOrder takes edges {u, v} meaning u comes before v; it returns nil if there is a cycle.
func topoOrder(n int, edges [][2]int) []int {
	graph := make([][]int, n)
	indeg := make([]int, n)
	for _, e := range edges {
		graph[e[0]] = append(graph[e[0]], e[1])
		indeg[e[1]]++
	}
	var q []int
	for i, d := range indeg {
		if d == 0 {
			q = append(q, i)
		}
	}
	order := make([]int, 0, n)
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		order = append(order, u)
		for _, v := range graph[u] {
			indeg[v]--
			if indeg[v] == 0 { // every prerequisite of v is placed
				q = append(q, v)
			}
		}
	}
	if len(order) < n {
		return nil
	}
	return order
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Three-colour DFS: grey is the current pathO(V + E) time · O(V) space

To detect cycles, or find nodes that can never reach one, with DFS: white is unvisited, grey is on the current recursion path, black is finished and known safe. Meeting a grey node means returning to the path, which is a cycle. LC 802 (Find Eventual Safe States) and the DFS take on LC 207 (Course Schedule).

Python
def eventual_safe_nodes(graph: list[list[int]]) -> list[int]:
    """Nodes every path from which ends at a terminal node: no cycle is reachable (LC 802)."""
    WHITE, GRAY, BLACK = 0, 1, 2  # unvisited / on the current DFS path / finished and safe
    color = [WHITE] * len(graph)

    def safe(u: int) -> bool:
        if color[u] != WHITE:
            return color[u] == BLACK  # GRAY: back on the current path, so a cycle
        color[u] = GRAY
        if not all(safe(v) for v in graph[u]):
            return False  # stays GRAY: on a cycle or leading to one
        color[u] = BLACK
        return True

    return [u for u in range(len(graph)) if safe(u)]
C++
// Nodes every path from which ends at a terminal node: no cycle is reachable (LC 802).
vector<int> eventualSafeNodes(const vector<vector<int>>& graph) {
    enum { WHITE, GRAY, BLACK };  // unvisited / on the current DFS path / finished and safe
    vector<int> color(graph.size(), WHITE);
    function<bool(int)> safe = [&](int u) {
        if (color[u] != WHITE) return color[u] == BLACK;  // GRAY: back on the current path, so a cycle
        color[u] = GRAY;
        for (int v : graph[u])
            if (!safe(v)) return false;  // stays GRAY: on a cycle or leading to one
        color[u] = BLACK;
        return true;
    };
    vector<int> res;
    for (int u = 0; u < (int)graph.size(); u++)
        if (safe(u)) res.push_back(u);
    return res;
}
Java
class Solution {
    private static final int WHITE = 0, GRAY = 1, BLACK = 2; // unvisited / on the current DFS path / finished and safe
    private int[][] graph;
    private int[] color;

    // Nodes every path from which ends at a terminal node: no cycle is reachable (LC 802).
    List<Integer> eventualSafeNodes(int[][] graph) {
        this.graph = graph;
        color = new int[graph.length];
        List<Integer> res = new ArrayList<>();
        for (int u = 0; u < graph.length; u++)
            if (safe(u)) res.add(u);
        return res;
    }

    private boolean safe(int u) {
        if (color[u] != WHITE) return color[u] == BLACK; // GRAY: back on the current path, so a cycle
        color[u] = GRAY;
        for (int v : graph[u])
            if (!safe(v)) return false; // stays GRAY: on a cycle or leading to one
        color[u] = BLACK;
        return true;
    }
}
Go
// eventualSafeNodes returns the nodes every path from which ends at a terminal node (LC 802).
func eventualSafeNodes(graph [][]int) []int {
	const (
		white = iota // unvisited
		gray         // on the current DFS path
		black        // finished and safe
	)
	color := make([]int, len(graph))
	var safe func(u int) bool
	safe = func(u int) bool {
		if color[u] != white {
			return color[u] == black // gray: back on the current path, so a cycle
		}
		color[u] = gray
		for _, v := range graph[u] {
			if !safe(v) {
				return false // stays gray: on a cycle or leading to one
			}
		}
		color[u] = black
		return true
	}
	res := []int{}
	for u := range graph {
		if safe(u) {
			res = append(res, u)
		}
	}
	return res
}
DP along a topological order: longest path, fewest termsO(V + E) time · O(V + E) space

When dependencies form a DAG and the question is the earliest finishing time or the longest chain: follow Kahn's dequeue order and, for each edge u→v, update term[v] from term[u] + 1 (or plus u's duration). LC 1136 (Parallel Courses); LC 2050 (Parallel Courses III) swaps the +1 for course durations.

Python
from collections import deque


def min_semesters(n: int, relations: list[tuple[int, int]]) -> int:
    """Courses 1..n, (a, b): a before b, any number per term. Fewest terms, or -1 on a cycle (LC 1136)."""
    graph = [[] for _ in range(n + 1)]
    indeg = [0] * (n + 1)
    for a, b in relations:
        graph[a].append(b)
        indeg[b] += 1
    term = [1] * (n + 1)  # term[v]: the earliest term v can be taken
    q = deque(v for v in range(1, n + 1) if indeg[v] == 0)
    done = 0
    while q:
        u = q.popleft()
        done += 1
        for v in graph[u]:
            term[v] = max(term[v], term[u] + 1)  # DP in topological order: u is final when it leaves
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return max(term[1:]) if done == n else -1
C++
// Courses 1..n, {a, b}: a before b, any number per term. Fewest terms, or -1 on a cycle (LC 1136).
int minSemesters(int n, const vector<pair<int, int>>& relations) {
    vector<vector<int>> graph(n + 1);
    vector<int> indeg(n + 1, 0), term(n + 1, 1);  // term[v]: the earliest term v can be taken
    for (auto [a, b] : relations) {
        graph[a].push_back(b);
        indeg[b]++;
    }
    queue<int> q;
    for (int v = 1; v <= n; v++)
        if (indeg[v] == 0) q.push(v);
    int done = 0;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        done++;
        for (int v : graph[u]) {
            term[v] = max(term[v], term[u] + 1);  // DP in topological order: u is final when it leaves
            if (--indeg[v] == 0) q.push(v);
        }
    }
    return done == n ? *max_element(term.begin() + 1, term.end()) : -1;
}
Java
class Solution {
    // Courses 1..n, {a, b}: a before b, any number per term. Fewest terms, or -1 on a cycle (LC 1136).
    int minSemesters(int n, int[][] relations) {
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
        int[] indeg = new int[n + 1], term = new int[n + 1]; // term[v]: the earliest term v can be taken
        Arrays.fill(term, 1);
        for (int[] r : relations) {
            graph.get(r[0]).add(r[1]);
            indeg[r[1]]++;
        }
        Deque<Integer> q = new ArrayDeque<>();
        for (int v = 1; v <= n; v++)
            if (indeg[v] == 0) q.offer(v);
        int done = 0, best = 0;
        while (!q.isEmpty()) {
            int u = q.poll();
            done++;
            best = Math.max(best, term[u]);
            for (int v : graph.get(u)) {
                term[v] = Math.max(term[v], term[u] + 1); // DP in topological order: u is final when it leaves
                if (--indeg[v] == 0) q.offer(v);
            }
        }
        return done == n ? best : -1;
    }
}
Go
// minSemesters returns the fewest terms for courses 1..n ({a, b}: a before b), or -1 on a cycle.
func minSemesters(n int, relations [][2]int) int {
	graph := make([][]int, n+1)
	indeg, term := make([]int, n+1), make([]int, n+1) // term[v]: the earliest term v can be taken
	for _, r := range relations {
		graph[r[0]] = append(graph[r[0]], r[1])
		indeg[r[1]]++
	}
	var q []int
	for v := 1; v <= n; v++ {
		term[v] = 1
		if indeg[v] == 0 {
			q = append(q, v)
		}
	}
	done, best := 0, 0
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		done++
		best = max(best, term[u])
		for _, v := range graph[u] {
			term[v] = max(term[v], term[u]+1) // DP in topological order: u is final when it leaves
			indeg[v]--
			if indeg[v] == 0 {
				q = append(q, v)
			}
		}
	}
	if done != n {
		return -1
	}
	return best
}

Why it works

  1. A node with in-degree 0 has no unfinished prerequisites, so placing it next violates no edge; removing its out-edges leaves the same problem on a smaller graph.
  2. On a cycle, every node keeps in-degree at least 1 because its predecessor on the cycle is never output, so fewer than n output nodes means exactly that the graph has a cycle.
  3. Every DAG has at least one node with in-degree 0 (otherwise walking backwards along incoming edges would eventually repeat a node and form a cycle), so without a cycle the queue never runs dry early.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
拓扑排序我用 Kahn 算法:先统计入度,把入度为 0 的点入队;每取出一个点就放进结果,并把它指向的点入度减一,减到 0 就入队。入度为 0 意味着前驱都已完成,所以放在这里不会违反依赖。如果最后输出的点少于 n,说明图中有环(剩下的点要么在环上,要么在环的下游),课程表这类题就是靠这个判断。时间 O(V + E)。
English
For topological order I use Kahn's algorithm: count in-degrees and enqueue every node with none. Each node I dequeue goes into the result, and every node it points to loses one in-degree and is enqueued when it reaches zero. In-degree zero means all its prerequisites are done, so placing it violates nothing. If fewer than n nodes come out, the graph has a cycle (every leftover node is on one or downstream of one), which answers course schedule problems, all in O(V + E).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. Kahn's algorithm (repeatedly removing in-degree-0 vertices) outputs fewer than n vertices. What does that mean?
  2. DFS-based topological sort outputs which order?
  3. V = n vertices and E = len(edges) edges. What is the time complexity?
    from collections import deque
    
    def topo(n, edges):
        adj = [[] for _ in range(n)]
        indeg = [0] * n
        for u, v in edges:
            adj[u].append(v)
            indeg[v] += 1
        q = deque(i for i in range(n) if indeg[i] == 0)
        order = []
        while q:
            u = q.popleft()
            order.append(u)
            for v in adj[u]:
                indeg[v] -= 1
                if indeg[v] == 0:
                    q.append(v)
        return order

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

from collections import deque


def topo_order(n: int, edges: list[tuple[int, int]]) -> list[int]:
    """Edge (u, v) means u comes before v. Returns [] if there is a cycle."""
    graph = [[] for _ in range(n)]
                q.append(v)
    return order if len(order) == n else []

Practice by stage

This stop's 7 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 1

#ProblemApproachRating
207Course ScheduleModel prerequisites as a directed graph and detect cycles through topological sorting.

Core 4

#ProblemApproachRating
210Course Schedule IIExtend cycle detection to produce a valid course order.
269Alien Dictionary 🔒Extract character dependencies from adjacent words and handle invalid prefixes and cycles.
802Find Eventual Safe StatesIdentify safe states that eventually reach terminal nodes, distinguishing the current recursion path from resolved states.Rating 1962
1136Parallel Courses 🔒Process courses in parallel by topological layer to find the minimum number of semesters.Rating 1710

Advanced 2

#ProblemApproachRating
1462Course Schedule IVCompute transitive prerequisite reachability to answer repeated relationship queries.Rating 1693
2392Build a Matrix With ConditionsSolve row and column partial-order constraints separately, then combine them into matrix coordinates.Rating 1961

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.