Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u-v, vertex u comes before v in the ordering.
Note: Topological Sorting for a graph is not possible if the graph is not a DAG.
Example:
Input: V = 6, edges = [[2, 3], [3, 1], [4, 0], [4, 1], [5, 0], [5, 2]]
ExampleOutput: 5 4 2 3 1 0
Explanation: The first vertex in topological sorting is always a vertex with an in-degree of 0 (a vertex with no incoming edges). A topological sorting of the following graph is "5 4 2 3 1 0". There can be more than one topological sorting for a graph. Another topological sorting of the following graph is "4 5 2 3 1 0".
Topological Sorting vs Depth First Traversal (DFS):
In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices.
For example, In the above given graph, the vertex '5' should be printed before vertex '0', but unlike DFS, the vertex '4' should also be printed before vertex '0'. So Topological sorting is different from DFS. For example, a DFS of the shown graph is "5 2 3 1 0 4", but it is not a topological sorting.
Topological Sorting in Directed Acyclic Graphs (DAGs)
DAGs are a special type of graphs in which each edge is directed such that no cycle exists in the graph, before understanding why Topological sort only exists for DAGs, lets first answer two questions:
- Why Topological Sort is not possible for graphs with undirected edges?
This is due to the fact that undirected edge between two vertices u and v means, there is an edge from u to v as well as from v to u. Because of this both the nodes u and v depend upon each other and none of them can appear before the other in the topological ordering without creating a contradiction.
- Why Topological Sort is not possible for graphs having cycles?
Imagine a graph with 3 vertices and edges = {1 to 2 , 2 to 3, 3 to 1} forming a cycle. Now if we try to topologically sort this graph starting from any vertex, it will always create a contradiction to our definition. All the vertices in a cycle are indirectly dependent on each other hence topological sorting fails.
Topological order may not be Unique:
Topological sorting is a dependency problem in which completion of one task depends upon the completion of several other tasks whose order can vary. Let us understand this concept via an example:
Suppose our task is to reach our School and in order to reach there, first we need to get dressed. The dependencies to wear clothes is shown in the below dependency graph. For example you can not wear shoes before wearing socks.

From the above image you would have already realized that there exist multiple ways to get dressed, the below image shows some of those ways.

Can you list all the possible topological ordering of getting dressed for above dependency graph?
Algorithm for Topological Sorting using DFS:
Here’s a step-by-step algorithm for topological sorting using Depth First Search (DFS):
- Create a graph with n vertices and m-directed edges.
- Initialize a stack and a visited array of size n.
- For each unvisited vertex in the graph, do the following:
- Call the DFS function with the vertex as the parameter.
- In the DFS function, mark the vertex as visited and recursively call the DFS function for all unvisited neighbors of the vertex.
- Once all the neighbors have been visited, push the vertex onto the stack.
- After all, vertices have been visited, pop elements from the stack and append them to the output list until the stack is empty.
- The resulting list is the topologically sorted order of the graph.
Illustration Topological Sorting Algorithm:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to perform DFS and topological sorting
void topologicalSortUtil(int v, vector<vector<int>> &adj, vector<bool> &visited, stack<int> &st)
{
// Mark the current node as visited
visited[v] = true;
// Recur for all adjacent vertices
for (int i : adj[v])
{
if (!visited[i])
topologicalSortUtil(i, adj, visited, st);
}
// Push current vertex to stack which stores the result
st.push(v);
}
vector<vector<int>> constructadj(int V, vector<vector<int>> &edges)
{
vector<vector<int>> adj(V);
for (auto it : edges)
{
adj[it[0]].push_back(it[1]);
}
return adj;
}
// Function to perform Topological Sort
vector<int> topologicalSort(int V, vector<vector<int>> &edges)
{
// Stack to store the result
stack<int> st;
vector<bool> visited(V, false);
vector<vector<int>> adj = constructadj(V, edges);
// Call the recursive helper function to store
// Topological Sort starting from all vertices one by
// one
for (int i = 0; i < V; i++)
{
if (!visited[i])
topologicalSortUtil(i, adj, visited, st);
}
vector<int> ans;
// Append contents of stack
while (!st.empty())
{
ans.push_back(st.top());
st.pop();
}
return ans;
}
int main()
{
// Graph represented as an adjacency list
int v = 6;
vector<vector<int>> edges = {{2, 3}, {3, 1}, {4, 0}, {4, 1}, {5, 0}, {5, 2}};
vector<int> ans = topologicalSort(v, edges);
for (auto node : ans)
{
cout << node << " ";
}
cout << endl;
return 0;
}
Java
import java.util.*;
class GfG {
private static void
topologicalSortUtil(int v, List<Integer>[] adj,
boolean[] visited,
Stack<Integer> stack)
{
visited[v] = true;
for (int i : adj[v]) {
if (!visited[i]) {
topologicalSortUtil(i, adj, visited, stack);
}
}
stack.push(v);
}
static List<Integer>[] constructadj(int V,
int[][] edges)
{
List<Integer>[] adj = new ArrayList[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
}
for (int[] edge : edges) {
adj[edge[0]].add(edge[1]);
}
return adj;
}
static int[] topologicalSort(int V, int[][] edges)
{
Stack<Integer> stack = new Stack<>();
boolean[] visited = new boolean[V];
List<Integer>[] adj = constructadj(V, edges);
for (int i = 0; i < V; i++) {
if (!visited[i]) {
topologicalSortUtil(i, adj, visited, stack);
}
}
int[] result = new int[V];
int index = 0;
while (!stack.isEmpty()) {
result[index++] = stack.pop();
}
return result;
}
public static void main(String[] args)
{
int v = 6;
int[][] edges = {{2, 3}, {3, 1}, {4, 0},
{4, 1}, {5, 0}, {5, 2}};
int[] ans = topologicalSort(v, edges);
for (int node : ans) {
System.out.print(node + " ");
}
System.out.println();
}
}
Python
# Function to perform DFS and topological sorting
def topologicalSortUtil(v, adj, visited, stack):
# Mark the current node as visited
visited[v] = True
# Recur for all adjacent vertices
for i in adj[v]:
if not visited[i]:
topologicalSortUtil(i, adj, visited, stack)
# Push current vertex to stack which stores the result
stack.append(v)
def constructadj(V, edges):
adj = [[] for _ in range(V)]
for it in edges:
adj[it[0]].append(it[1])
return adj
# Function to perform Topological Sort
def topologicalSort(V, edges):
# Stack to store the result
stack = []
visited = [False] * V
adj = constructadj(V, edges)
# Call the recursive helper function to store
# Topological Sort starting from all vertices one by one
for i in range(V):
if not visited[i]:
topologicalSortUtil(i, adj, visited, stack)
# Reverse stack to get the correct topological order
return stack[::-1]
if __name__ == '__main__':
# Graph represented as an adjacency list
v = 6
edges = [[2, 3], [3, 1], [4, 0], [4, 1], [5, 0], [5, 2]]
ans = topologicalSort(v, edges)
print(" ".join(map(str, ans)))
C#
using System;
using System.Collections.Generic;
class GfG {
static void TopologicalSortUtil(int v, List<int>[] adj,
bool[] visited,
Stack<int> stack)
{
visited[v] = true;
foreach(int i in adj[v])
{
if (!visited[i]) {
TopologicalSortUtil(i, adj, visited, stack);
}
}
stack.Push(v);
}
static List<int>[] constructadj(int V, int[][] edges)
{
List<int>[] adj = new List<int>[ V ];
for (int i = 0; i < V; i++) {
adj[i] = new List<int>();
}
foreach(int[] edge in edges)
{
adj[edge[0]].Add(edge[1]);
}
return adj;
}
static int[] TopologicalSort(int V, int[][] edges)
{
Stack<int> stack = new Stack<int>();
bool[] visited = new bool[V];
List<int>[] adj = constructadj(V, edges);
for (int i = 0; i < V; i++) {
if (!visited[i]) {
TopologicalSortUtil(i, adj, visited, stack);
}
}
int[] result = new int[V];
int index = 0;
while (stack.Count > 0) {
result[index++] = stack.Pop();
}
return result;
}
public static void Main()
{
int v = 6;
int[][] edges
= { new int[] {2, 3}, new int[] {3, 1},
new int[] {4, 0}, new int[] {4, 1},
new int[] {5, 0}, new int[] {5, 2} };
int[] ans = TopologicalSort(v, edges);
Console.WriteLine(string.Join(" ", ans));
}
}
JavaScript
// Function to perform DFS and topological sorting
function topologicalSortUtil(v, adj, visited, st)
{
// Mark the current node as visited
visited[v] = true;
// Recur for all adjacent vertices
for (let i of adj[v]) {
if (!visited[i])
topologicalSortUtil(i, adj, visited, st);
}
// Push current vertex to stack which stores the result
st.push(v);
}
function constructadj(V, edges)
{
let adj = Array.from(
{length : V},
() => []); // Fixed the adjacency list declaration
for (let it of edges) {
adj[it[0]].push(
it[1]); // Fixed adjacency list access
}
return adj;
}
// Function to perform Topological Sort
function topologicalSort(V, edges)
{
// Stack to store the result
let st = [];
let visited = new Array(V).fill(false);
let adj = constructadj(V, edges);
// Call the recursive helper function to store
// Topological Sort starting from all vertices one by
// one
for (let i = 0; i < V; i++) {
if (!visited[i])
topologicalSortUtil(i, adj, visited, st);
}
let ans = [];
// Append contents of stack
while (st.length > 0) {
ans.push(st.pop());
}
return ans;
}
// Main function
let v = 6;
let edges = [
[2, 3], [3, 1], [4, 0], [4, 1], [5, 0],
[5, 2]
];
let ans = topologicalSort(v, edges);
console.log(ans.join(" ") + " ");
Time Complexity: O(V+E). The above algorithm is simply DFS with an extra stack. So time complexity is the same as DFS.
Auxiliary space: O(V). due to creation of the stack.
We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.
Topological Sorting Using BFS:
The BFS based algorithm for Topological Sort is called Kahn's Algorithm. The Kahn's algorithm has same time complexity as the DFS based algorithm discussed above.
Advantages of Topological Sort:
- Helps in scheduling tasks or events based on dependencies.
- Detects cycles in a directed graph.
- Efficient for solving problems with precedence constraints.
Disadvantages of Topological Sort:
- Only applicable to directed acyclic graphs (DAGs), not suitable for cyclic graphs.
- May not be unique, multiple valid topological orderings can exist.
Applications of Topological Sort:
- Task scheduling and project management.
- In software deployment tools like Makefile.
- Dependency resolution in package management systems.
- Determining the order of compilation in software build systems.
- Deadlock detection in operating systems.
- Course scheduling in universities.
- It is used to find shortest paths in weighted directed acyclic graphs
Related Articles:
Topological sort | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem