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

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

  1. Run DFS from every unvisited node.
  2. During DFS, first recursively visit all neighbors (dependencies) of the current node.
  3. Once all neighbors have been fully processed, add the current node to the front of the result list (or push it onto a stack).
  4. 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

  1. DFS from A: visit C first (its dependency), then C's dependency D
  2. D has no dependencies, finish D, add to front → [D]
  3. Finish C, add to front → [C, D]
  4. Finish A, add to front → [A, C, D]
  5. DFS from B: C already visited, finish B, add to front → [B, A, C, D]

Output: One valid order: B, A, C, D

Graph: Introduction
A set of nodes connected by edges — edges can be one-way or two-way, and optionally carry a weight (cost/distance).
A
B
C
D
E
Unvisited Visited / discovered Current Start
Graph: Introduction
Press ▶ Run to watch it step by step.
Python · Graphs in Code
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 sort
Input: Tasks with dependencies: A->C, B->C, C->D

Behind 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

TimeO(V + E)
SpaceO(V) for the visited set and result structure

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.