GeeksforGeeks Medium

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).

Constraints
  • 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)
graphtoposortdfspost-order
Open on GeeksforGeeks ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1import sys
▶2 
▶3 
▶4class Solution:
▶5 def topoSort(self, V: int, edges: List[List[int]]) -> List[int]:
▶6 sys.setrecursionlimit(V + 1000)
▶7 adj = [[] for _ in range(V)]
▶8 for u, v in edges:
▶9 adj[u].append(v)
▶10 seen = [False] * V
▶11 finished = []
▶12 
▶13 def dfs(u: int) -> None:
▶14 seen[u] = True
▶15 for v in adj[u]:
▶16 if not seen[v]:
▶17 dfs(v)
▶18 finished.append(u)
▶19 
▶20 for s in range(V):
▶21 if not seen[s]:
▶22 dfs(s)
▶23 return finished[::-1]
on the call stackfinished012345call stackemptyfinishedanswernothing visited yet
V66 directed edges
finished[ ]filled as calls return
Idea. A vertex's place is only certain when its DFS call returns: by then everything it points to has already returned. So record vertices on the way out, and reverse that list at the end.
on the call stackfinished012345call stack0finishedanswer0 is unseen → start a search from it
s0outer loop
call stack[0]depth 1
finished[]
The outer loop starts at vertex 0, which is unseen, so it launches dfs(0). Which vertex we start from does not affect correctness.
on the call stackfinished012345call stack0✓finished0answer0 is done → add it to finished
u0all out-edges handled
finished[0]appended 0
call stack[]empty
0 has no outgoing edges, so nothing has to come after it and its call returns at once. Sinks finish early, which is why they end up late in the answer.
on the call stackfinished012345call stack1finished0answer1 is unseen → start a search from it
s1outer loop
call stack[1]depth 1
finished[0]
The outer loop reaches 1, which no earlier DFS reached, so it gets its own launch. Skipping this loop would leave such vertices out of the answer.
on the call stackfinished012345call stack1✓finished01answer1 is done → add it to finished
u1all out-edges handled
finished[0, 1]appended 1
call stack[]empty
1 has no outgoing edges, so nothing has to come after it and its call returns at once. Sinks finish early, which is why they end up late in the answer.
on the call stackfinished012345call stack2finished01answer2 is unseen → start a search from it
s2outer loop
call stack[2]depth 1
finished[0, 1]
The outer loop reaches 2, which no earlier DFS reached, so it gets its own launch. Skipping this loop would leave such vertices out of the answer.
on the call stackfinished012345call stack23finished01answer2 → 3: 3 is new, go deeper
u3entered from 2
call stack[2, 3]depth 2
finished[0, 1]
3 is unseen, so 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.
on the call stackfinished012345call stack23finished01answer3 → 1: 1 already finished, skip
edge3 → 1
seen[1]trueand finished
finished[0, 1]
1 is already in 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.
on the call stackfinished012345call stack23✓finished013answer3 is done → add it to finished
u3all out-edges handled
finished[0, 1, 3]appended 3
call stack[2]back in dfs(2)
Every edge out of 3 (to 1) has been handled, so everything reachable from 3 is already in the list. Appending 3 now puts it after all of them.
on the call stackfinished012345call stack2✓finished0132answer2 is done → add it to finished
u2all out-edges handled
finished[0, 1, 3, 2]appended 2
call stack[]empty
Every edge out of 2 (to 3) has been handled, so everything reachable from 2 is already in the list. Appending 2 now puts it after all of them.
on the call stackfinished012345call stack4finished0132answer4 is unseen → start a search from it
s4outer loop
call stack[4]depth 1
finished[0, 1, 3, 2]
The outer loop reaches 4, which no earlier DFS reached, so it gets its own launch. Skipping this loop would leave such vertices out of the answer.
on the call stackfinished012345call stack4finished0132answer4 → 0: 0 already finished, skip
edge4 → 0
seen[0]trueand finished
finished[0, 1, 3, 2]
0 is already in 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.
on the call stackfinished012345call stack4finished0132answer4 → 1: 1 already finished, skip
edge4 → 1
seen[1]trueand finished
finished[0, 1, 3, 2]
1 is already in 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.
on the call stackfinished012345call stack4✓finished01324answer4 is done → add it to finished
u4all out-edges handled
finished[0, 1, 3, 2, 4]appended 4
call stack[]empty
Every edge out of 4 (to 0 and 1) has been handled, so everything reachable from 4 is already in the list. Appending 4 now puts it after all of them.
on the call stackfinished012345call stack5finished01324answer5 is unseen → start a search from it
s5outer loop
call stack[5]depth 1
finished[0, 1, 3, 2, 4]
The outer loop reaches 5, which no earlier DFS reached, so it gets its own launch. Skipping this loop would leave such vertices out of the answer.
on the call stackfinished012345call stack5finished01324answer5 → 2: 2 already finished, skip
edge5 → 2
seen[2]trueand finished
finished[0, 1, 3, 2, 4]
2 is already in 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.
on the call stackfinished012345call stack5finished01324answer5 → 0: 0 already finished, skip
edge5 → 0
seen[0]trueand finished
finished[0, 1, 3, 2, 4]
0 is already in 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.
on the call stackfinished012345call stack5✓finished013245answer5 is done → add it to finished
u5all out-edges handled
finished[0, 1, 3, 2, 4, 5]appended 5
call stack[]empty
Every edge out of 5 (to 2 and 0) has been handled, so everything reachable from 5 is already in the list. Appending 5 now puts it after all of them.
on the call stackfinished012345call stackemptyfinished013245reverse ↓542310answer = finished, reversedreverse finished → the answer
finished[0, 1, 3, 2, 4, 5]post-order
answer[5, 4, 2, 3, 1, 0]finished reversed
The last vertex to finish, 5, is a source: a vertex with an edge into it would have had to finish after it. Reversing the finish list puts it first and every vertex ahead of its descendants.
on the call stackfinished012345call stackemptyfinished013245reverse ↓542310answer, with every edge drawnall 6 edges point right
answer[5, 4, 2, 3, 1, 0]a valid topological order
edges6all point left to right
Check. Drawn over the answer, every edge runs left to right. That is the proof in action: for each edge u → v, v finished before u, so after the reversal u is in front. Recording on entry instead would give [0, 1, 2, 3, 4, 5], where 5 → 2 points backward.
05

Common pitfalls

Appending when the vertex is entered

✗ Wrong
def dfs(u):
    seen[u] = True
    finished.append(u)
    for v in adj[u]:
        ...
✓ Right
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

✗ Wrong
return finished
✓ Right
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

✗ Wrong
dfs(0)
return finished[::-1]
✓ Right
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.

06

Edge cases

Vertices with no edges

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.

Input that contains a cycle

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.

A chain of 5,000 vertices

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].

07

Complexity

Time
O(V + E)
Space
O(V + E)
Each vertex is entered and finished once and each edge is checked once. The adjacency list takes O(V + E); seen, finished and the recursion stack take O(V).
08

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-orderKahn's algorithm (BFS)
Tracksa seen flag per vertexan in-degree count per vertex
Order is builtback to front, then reversedfront to back, as vertices hit in-degree 0
First vertex placeda sink (nothing left to explore)a source (nothing points into it)
Cycle in the inputsilent unless you add a third statedetected: fewer than V vertices come out
Recursionyes, up to V deepno, a plain queue
09

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.