AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsGraphsTopological Sort
Graphsintermediatedagorderingschedulingdfs

Topological Sort

Topological Sort produces a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge u→v, u appears before v. It is implemented with DFS (reverse finish order) or Kahn's BFS algorithm (process nodes with in-degree 0 first). Used for task scheduling and dependency resolution.

Complexity

Best
O(V+E)
Average
O(V+E)
Worst
O(V+E)
Space
O(V)

Visualizer

Implementation

void dfsTopoSort(int v, vector<vector<int>>& adj, vector<bool>& visited, stack<int>& stk) {
    visited[v]=true;
    for(int u:adj[v]) if(!visited[u]) dfsTopoSort(u,adj,visited,stk);
    stk.push(v);
}
vector<int> topoSort(int n, vector<vector<int>>& adj){
    vector<bool> visited(n,false); stack<int> stk;
    for(int i=0;i<n;i++) if(!visited[i]) dfsTopoSort(i,adj,visited,stk);
    vector<int> order;
    while(!stk.empty()){order.push_back(stk.top());stk.pop();}
    return order;
}

How It Works

1.DAG Requirement

Topological sort only exists for Directed Acyclic Graphs. If the graph has a cycle, no valid ordering exists. The DFS-based algorithm implicitly detects cycles through back edges.

2.DFS Approach

Run DFS on the graph. When all descendants of a node are processed (DFS finishes), push the node onto a stack. Popping the stack gives the topological order.

3.Kahn's Algorithm

Alternatively: compute in-degrees of all nodes. Start a queue with all zero-in-degree nodes. Process each node and reduce in-degrees of its neighbors. Nodes reaching zero in-degree join the queue.

4.Applications

Topological sort is used for: build systems (make, Gradle), task scheduling with dependencies, course prerequisite ordering, and resolving symbol dependencies in linkers.

Related Algorithms

Share2Depth-First SearchShare2Kosaraju's SCCShare2Breadth-First Search

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms