Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
All Topological Sorts of a Directed Acyclic Graph
Next article icon

Topological Sorting

Last Updated : 04 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

example

Example

Output: 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”.

Table of Content

  • Topological Sorting vs Depth First Traversal (DFS): 
  • Topological Sorting in Directed Acyclic Graphs (DAGs)
  • Algorithm for Topological Sorting using DFS:
  • Topological Sorting Using BFS:
  • Advantages of Topological Sort:
  • Disadvantages of Topological Sort:
  • Applications of Topological Sort:

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.

1

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.

2

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(" ") + " "); 

Output
5 4 2 3 1 0  

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: 

  • Kahn’s algorithm for Topological Sorting
  • All Topological Sorts of a Directed Acyclic Graph




Next Article
All Topological Sorts of a Directed Acyclic Graph
author
kartik
Improve
Article Tags :
  • DSA
  • Graph
  • Accolite
  • Amazon
  • DFS
  • Flipkart
  • Microsoft
  • Moonfrog Labs
  • Morgan Stanley
  • OYO
  • Samsung
  • Topological Sorting
Practice Tags :
  • Accolite
  • Amazon
  • Flipkart
  • Microsoft
  • Moonfrog Labs
  • Morgan Stanley
  • Samsung
  • DFS
  • Graph

Similar Reads

  • Graph Algorithms
    Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
    3 min read
  • Introduction to Graph Data Structure
    Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
    15+ min read
  • Graph and its representations
    A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
    12 min read
  • Types of Graphs with Examples
    A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
    9 min read
  • Basic Properties of a Graph
    A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
    4 min read
  • Applications, Advantages and Disadvantages of Graph
    Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
    7 min read
  • Transpose graph
    Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
    9 min read
  • Difference Between Graph and Tree
    Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
    2 min read
  • BFS and DFS on Graph

    • Breadth First Search or BFS for a Graph
      Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
      15+ min read

    • Depth First Search or DFS for a Graph
      In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
      13 min read

    • Applications, Advantages and Disadvantages of Depth First Search (DFS)
      Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
      4 min read

    • Applications, Advantages and Disadvantages of Breadth First Search (BFS)
      We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
      4 min read

    • Iterative Depth First Traversal of Graph
      Given a directed Graph, the task is to perform Depth First Search of the given graph. Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list. Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pic
      10 min read

    • BFS for Disconnected Graph
      In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
      14 min read

    • Transitive Closure of a Graph using DFS
      Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
      8 min read

    • Difference between BFS and DFS
      Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
      2 min read

    Cycle in a Graph

    • Detect Cycle in a Directed Graph
      Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not. Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 0 Input: V = 4, edges[][] = [[0, 1], [0, 2
      15+ min read

    • Detect cycle in an undirected graph
      Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0 Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: falseExplana
      8 min read

    • Detect Cycle in a directed graph using colors
      Given a directed graph represented by the number of vertices V and a list of directed edges, determine whether the graph contains a cycle. Your task is to implement a function that accepts V (number of vertices) and edges (an array of directed edges where each edge is a pair [u, v]), and returns tru
      9 min read

    • Detect a negative cycle in a Graph | (Bellman Ford)
      Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
      15+ min read

    • Cycles of length n in an undirected and connected graph
      Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
      10 min read

    • Detecting negative cycle using Floyd Warshall
      We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
      12 min read

    • Clone a Directed Acyclic Graph
      A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
      12 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences