Topological Sort (template)
Count each vertex's in-degree once. Put every vertex with in-degree 0 in a queue. Pop a vertex, add it to the order, and lower the in-degree of each of its children by one. A child whose in-degree reaches 0 joins the queue. Nothing is ever recounted.
A vertex is safe to place when its in-degree is 0, which means every one of its parents is already in the order. So every edge into it already points forward.
Problem
You are given a directed acyclic graph (a DAG) with V vertices, numbered 0 to V − 1. Its E edges are given as a list edges, where edges[i] = [u, v] is an edge from u to v.
Return a list of all the vertices so that for every edge u → v, the vertex u comes before v in the list. A list like this is a topological order.
Many orders can be correct. Any one of them is accepted.
V, the number of vertices, and edges, a list of directed edges [u, v].
A list of all V vertices in a topological order.
Vertex 0 has three parents (3, 1 and 2), so it must come last. The other three can be in any order. Any order that ends with 0 is correct.
Vertices 4 and 5 have no parents, so they go first. In this list every edge points forward: 4 → 1, 4 → 0, 5 → 0, 5 → 2, 1 → 3 and 2 → 3.
- • 2 ≤ V ≤ 5 × 10^3
- • 1 ≤ E = edges.size() ≤ min(10^5, V · (V − 1) / 2)
- • 0 ≤ edges[i][0], edges[i][1] < V
- • The graph has no cycles.
First, think yourself
Before opening any solution, try to answer these on paper. Use hints only when stuck — each hint is counted.
- 1.
If an edge
u → vsays u must come before v, which vertex can I place first with no risk at all? - 2.
What does it mean for a vertex to have no incoming edges?
- 3.
After I place a vertex, which other vertices might become safe to place?
- 4.
How do I know when every vertex is placed, and what does it mean if I get stuck with some left?
- 5.
A plain DFS visit order also lists every vertex. Does it respect every edge? Try it on a small example.
Brute force approach
Optimized approach
Why does this algorithm work?
Dry run
All approaches compared
| Approach | Idea | Time | Space |
|---|---|---|---|
| Brute Force | Each round, recount in-degrees and place the first free vertex | O(V · (V + E)) | O(V) |
| Optimal | Queue every in-degree 0 vertex; placing one lowers its children's in-degree | O(V + E) | O(V + E) |
Why does this belong to this pattern?
- “directed graph with no cycles (DAG)”Edges have a direction and there is no loop, so some vertex must have no parents.
- “every edge goes forward in the order”Each vertex must come after all its parents, so the first vertex has in-degree 0.
- “any valid order is accepted”We need one order that respects every edge, not one exact answer. Kahn's queue gives one of many.
This is the template for the whole Topological Sort pattern: a vertex with no remaining parents is always safe to place, and placing it frees its children. The later questions in this sub-pattern keep the queue and change what they count or return: course order adds a cycle check, Parallel Courses counts levels, Parallel Courses III adds durations. The pattern confusion to avoid is a plain traversal: DFS or BFS visit order follows the edges from a start point, not the rule parents first.
Don't make this mistake
A visit order goes where the edges lead, not parents first. On V = 6, edges 5→2, 5→0, 4→0, 4→1, 2→3, 3→1, the DFS above prints 0, 1, 2, 3, 4, 5. That puts 2 before 5, but 5 → 2 is an edge, so the answer is wrong. Traversals answer "what can I reach?". Topological sort answers "what must come first?".
A vertex with no edges at all is never queued. On V = 5, edges [[3,0],[1,0],[2,0]], vertex 4 has no edges, so the answer comes out as [3, 1, 2, 0]: only 4 vertices, not 5. Every vertex with in-degree 0 must be queued, including the isolated ones.
A vertex finishes only after everything it points to has finished, so the finish list is the reverse of a topological order. On the dry-run graph, DFS from 0 to 5 finishes in [0, 1, 3, 2, 4, 5]. That has 2 before 5, which is backwards. Reversed it becomes [5, 4, 2, 3, 1, 0], which is valid. Kahn's queue needs no reversing.
Want to implement this?
Write it yourself on GeeksforGeeks, then come back and compare your code with the solutions above.
Open coding workspaceHow this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Topological Sort translate into production architectures and low-level memory mechanics.