Topological Sort (DFS)
Topological Sort (DFS) is a GFG problem (Medium). You get V vertices numbered 0 to V - 1 and a list edges, where edges[i] = [u, v] is a directed edge from u to v. The graph is a DAG: directed, with no cycle.
Return an ordering of all V vertices in which, for every edge u → v, u comes before v. That ordering is a topological sort.
- Several orders are usually valid, and the judge accepts any of them.
- The graph may be disconnected, and some vertices may have no edges. Every vertex still appears exactly once.
- This page uses depth-first search. The queue-based version is Kahn's algorithm.
With up to 5,000 vertices and 10⁵ edges, the sort has to visit each vertex and edge once: O(V + E).
- 2 <= V <= 5 × 10³
- 1 <= E = edges.length <= min(10⁵, V(V − 1) / 2)
- 0 <= edges[i][0], edges[i][1] < V
- The graph is a directed acyclic graph (DAG)
Intuition
Read an edge u → v as "u must come before v". During a DFS, when do we know where u belongs?
Not when we enter u: we have not looked at what it points to yet. But when the call for u returns, every vertex reachable from u has already been explored and has already returned. Everything that must come after u is settled.
So a topological sort using DFS is one rule: append each vertex when its call returns, then reverse the list. The finish list has every vertex after the vertices it points to; reversed, every vertex sits before them, which is exactly what each edge asks for.
Reach for a DFS based topological sort whenever items have "must come before" rules and you need a full order: build steps, course prerequisites, spreadsheet recalculation, package installs. Course Schedule II (210) and Alien Dictionary (269) use the same pattern, with a cycle check added because their input is not promised to be a DAG.
Approach
Before reading on, take the edges 0 → 1, 0 → 2, 2 → 1. Run a DFS from 0 and write down vertices in the order you first visit them. Is that a valid order? Now write them in the order their calls return, and reverse. Aim for O(V + E).
Build the adjacency list
For each [u, v], add v to adj[u]. Only outgoing edges are needed, because the DFS only ever walks forward along them. Unlike Kahn's algorithm, there is no in-degree array to keep.
Append each vertex on the way out
dfs(u) marks u seen, calls itself on every unseen neighbour, and only then appends u to finished. The append is the last line, after the loop, because only then has everything reachable from u been placed.
Start a search from every unseen vertex
Loop s over 0 to V - 1 and call dfs(s) whenever s is still unseen. One search only reaches what its start vertex can reach, so vertices with no incoming edge, or in another component, need their own start. The start order does not affect correctness.
Reverse the finish list
finished holds the vertices in reverse topological order, so return it reversed. Pushing onto a stack and popping everything off does the same job. The reversal is a single O(V) pass.
Why every edge ends up pointing forward
When dfs(u) looks at an edge u → v, either v is unseen, so dfs(v) runs and returns first, or v has already finished. (If v were still on the call stack, u → v would close a cycle.) Either way v finishes before u, so after the reversal u comes first.
Code in Python, C++ and Java
dfs(0). Which vertex we start from does not affect correctness.dfs(2) pauses and calls dfs(3). 2 cannot finish until 3 has, which is exactly what will put 3 after 2 in the answer.finished, ahead of 3. When 3 finishes it lands after 1, so after the reversal 3 comes first, as the edge demands. Nothing to do.finished, ahead of 4. When 4 finishes it lands after 0, so after the reversal 4 comes first, as the edge demands. Nothing to do.finished, ahead of 4. When 4 finishes it lands after 1, so after the reversal 4 comes first, as the edge demands. Nothing to do.finished, ahead of 5. When 5 finishes it lands after 2, so after the reversal 5 comes first, as the edge demands. Nothing to do.finished, ahead of 5. When 5 finishes it lands after 0, so after the reversal 5 comes first, as the edge demands. Nothing to do.dfs(0). Which vertex we start from does not affect correctness.dfs(0) pauses and calls dfs(1). 0 cannot finish until 1 has, which is exactly what will put 1 after 0 in the answer.dfs(0) pauses and calls dfs(2). 0 cannot finish until 2 has, which is exactly what will put 2 after 0 in the answer.finished, ahead of 2. When 2 finishes it lands after 1, so after the reversal 2 comes first, as the edge demands. Nothing to do.dfs(0). Which vertex we start from does not affect correctness.dfs(0) pauses and calls dfs(1). 0 cannot finish until 1 has, which is exactly what will put 1 after 0 in the answer.dfs(1) pauses and calls dfs(2). 1 cannot finish until 2 has, which is exactly what will put 2 after 1 in the answer.seen check cannot tell this apart from a finished vertex, so it skips the edge silently.Common pitfalls
Appending when the vertex is entered
def dfs(u):
seen[u] = True
finished.append(u)
for v in adj[u]:
...def dfs(u):
seen[u] = True
for v in adj[u]:
...
finished.append(u)That records pre-order, the order vertices are discovered. With 0 → 1, 0 → 2, 2 → 1, pre-order is 0 1 2, which puts 1 before 2 against the edge 2 → 1. It only looks right on a straight chain.
Returning the finish list as it is
return finished
return finished[::-1]
Post-order puts each vertex after everything it points to, so the unreversed list has every edge pointing backward. It is a valid order for the reversed graph, not this one.
Launching DFS only from vertex 0
dfs(0) return finished[::-1]
for s in range(V):
if not seen[s]:
dfs(s)One search only reaches what vertex 0 can reach. With the single edge 1 → 0, dfs(0) visits only 0 and the answer is [0]: vertex 1 is never placed. The answer must contain all V vertices.
Edge cases
The outer loop starts a search on each one; it finishes at once and lands somewhere in the order. Any position is valid, because no edge constrains it.
The code still returns V vertices, but at least one edge points backward and nothing signals it. If the input is not promised to be a DAG, give each vertex three states (unseen, on the call stack, finished) and fail when an edge reaches a vertex that is still on the call stack.
The recursion goes V calls deep, past Python's default limit of 1,000, so the Python code raises the limit. To avoid deep recursion in any language, keep an explicit stack of (vertex, next neighbour index) pairs and append a vertex when its index runs past the end of adj[u].
Complexity
seen, finished and the recursion stack take O(V).DFS post-order vs Kahn's algorithm
Both give a valid topological sort in O(V + E). They differ in what they track and in what happens on a cycle.
| DFS post-order | Kahn's algorithm (BFS) | |
|---|---|---|
| Tracks | a seen flag per vertex | an in-degree count per vertex |
| Order is built | back to front, then reversed | front to back, as vertices hit in-degree 0 |
| First vertex placed | a sink (nothing left to explore) | a source (nothing points into it) |
| Cycle in the input | silent unless you add a third state | detected: fewer than V vertices come out |
| Recursion | yes, up to V deep | no, a plain queue |
Topological Sort (DFS) FAQ
Why is a stack used in a DFS topological sort?
DFS finishes vertices in reverse topological order: sinks first, sources last. Pushing each vertex onto a stack as it finishes and popping them all at the end flips that order for free. A list reversed once at the end does the same thing.
Is the topological order unique?
Only when the order is forced, which happens when consecutive vertices in it are always joined by an edge (a path through every vertex). Otherwise several orders are valid, and the one DFS returns depends on the start order and the order of each adjacency list.