Data Structures · Visualization
Graph: Topological Sort
Graph
A topological sort arranges the nodes of a directed acyclic graph (a graph with directed edges and no cycles) into a linear order where every edge points from an earlier node to a later one. Time: O(V + E). Space: O(V) for the visited set and result structure.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Topological Sort
GraphA topological sort arranges the nodes of a directed acyclic graph (a graph with directed edges and no cycles) into a linear order where every edge points from an earlier node to a later one. This is only possible if the graph has no cycles, and it's commonly computed using DFS: recursively visit all of a node's dependencies first, then add the node to the front of the result once all its dependencies are done.
How Topological Sort Works
- Run DFS from every unvisited node.
- During DFS, first recursively visit all neighbors (dependencies) of the current node.
- Once all neighbors have been fully processed, add the current node to the front of the result list (or push it onto a stack).
- After DFS finishes for all nodes, the result list is a valid topological order.
Topological Sort Worked Example
Input: Tasks with dependencies: A->C, B->C, C->D
- DFS from A: visit C first (its dependency), then C's dependency D
- D has no dependencies, finish D, add to front → [D]
- Finish C, add to front → [C, D]
- Finish A, add to front → [A, C, D]
- DFS from B: C already visited, finish B, add to front → [B, A, C, D]
Output: One valid order: B, A, C, D
Press ▶ Run to watch it step by step.
from collections import defaultdict, deque
def topo_sort(vertices, edges):
indeg = {v: 0 for v in vertices}
adj = defaultdict(list)
for a, b in edges:
adj[a].append(b)
indeg[b] += 1
q = deque([v for v in vertices if indeg[v] == 0])
order = []
while q:
v = q.popleft()
order.append(v)
for nxt in adj[v]:
indeg[nxt] -= 1
if indeg[nxt] == 0:
q.append(nxt)
return order if len(order) == len(vertices) else []
# example: topological sortBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Topological Sort Time & Space Complexity
When to Use Topological Sort
- Determining a valid build order for software with dependencies
- Course scheduling based on prerequisites
- Task scheduling where some tasks must happen before others
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.