Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
All Topological Sorts of a Directed Acyclic Graph
Next article icon

Topological Sorting in Python

Last Updated : 04 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.

Example: 

Input: Graph :

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

Topological sorting can be implemented recursively and non-recursively. First, we show the clearer recursive version, then provide the non-recursive version with analysis.

Recursive DFS-Based Topological Sorting

This approach uses Depth-First Search (DFS) and recursion to find the topological order of a Directed Acyclic Graph (DAG). It explores all dependencies first and then adds the node to a stack, ensuring the correct order. The final sequence is obtained by reversing the stack.

Python
from collections import defaultdict  #Class to represent a graph class Graph:     def __init__(self,vertices):         self.graph = defaultdict(list) #dictionary containing adjacency List         self.V = vertices #No. of vertices      # function to add an edge to graph     def addEdge(self,u,v):         self.graph[u].append(v)      # A recursive function used by topologicalSort     def topologicalSortUtil(self,v,visited,stack):          # Mark the current node as visited.         visited[v] = True          # Recur for all the vertices adjacent to this vertex         for i in self.graph[v]:             if visited[i] == False:                 self.topologicalSortUtil(i,visited,stack)          # Push current vertex to stack which stores result         stack.insert(0,v)      # The function to do Topological Sort. It uses recursive     # topologicalSortUtil()     def topologicalSort(self):         # Mark all the vertices as not visited         visited = [False]*self.V         stack =[]          # Call the recursive helper function to store Topological         # Sort starting from all vertices one by one         for i in range(self.V):             if visited[i] == False:                 self.topologicalSortUtil(i,visited,stack)          # Print contents of stack         print (stack)  g= Graph(6) g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1);  print ("Following is a Topological Sort of the given graph") g.topologicalSort() 

Output
Following is a Topological Sort of the given graph [5, 4, 2, 3, 1, 0]

Iterative DFS-Based Topological Sorting

This method eliminates recursion and uses an explicit stack to simulate DFS traversal. It employs generators for efficient neighbor iteration and manually manages backtracking. This approach is useful for handling large graphs without hitting recursion limits.

Algorithm:

The way topological sorting is solved is by processing a node after all of its children are processed. Each time a node is processed, it is pushed onto a stack in order to save the final result. This non-recursive solution builds on the same concept of DFS with a little tweak which can be understood above and in this article.

However, unlike the recursive solution, which saves the order of the nodes in the stack after all the neighboring elements have been pushed to the program stack, this solution replaces the program stack with a working stack. If a node has a neighbor that has not been visited, the current node and the neighbor are pushed to the working stack to be processed until there are no more neighbors available to be visited.

After all the nodes have been visited, what remains is the final result which is found by printing the stack result in reverse.

Python
from collections import defaultdict  #Class to represent a graph class Graph:     def __init__(self,vertices):         self.graph = defaultdict(list) #dictionary containing adjacency List         self.V = vertices #No. of vertices      # function to add an edge to graph     def addEdge(self,u,v):         self.graph[u].append(v)      # neighbors generator given key     def neighbor_gen(self,v):         for k in self.graph[v]:             yield k          # non recursive topological sort     def nonRecursiveTopologicalSortUtil(self, v, visited,stack):                  # working stack contains key and the corresponding current generator         working_stack = [(v,self.neighbor_gen(v))]                  while working_stack:             # get last element from stack             v, gen = working_stack.pop()             visited[v] = True                          # run through neighbor generator until it's empty             for next_neighbor in gen:                 if not visited[next_neighbor]: # not seen before?                     # remember current work                     working_stack.append((v,gen))                     # restart with new neighbor                     working_stack.append((next_neighbor, self.neighbor_gen(next_neighbor)))                     break             else:                 # no already-visited neighbor (or no more of them)                 stack.append(v)                      # The function to do Topological Sort.     def nonRecursiveTopologicalSort(self):         # Mark all the vertices as not visited         visited = [False]*self.V                  # result stack         stack = []          # Call the helper function to store Topological         # Sort starting from all vertices one by one         for i in range(self.V):             if not(visited[i]):                 self.nonRecursiveTopologicalSortUtil(i, visited,stack)         # Print contents of the stack in reverse         stack.reverse()         print(stack)  g= Graph(6) g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1);  print("The following is a Topological Sort of the given graph") g.nonRecursiveTopologicalSort() 

Output
The following is a Topological Sort of the given graph [5, 4, 2, 3, 1, 0]

Complexity Analysis:

  • Time Complexity: O(V + E): The above algorithm is simply DFS with a working stack and a result stack. Unlike the recursive solution, recursion depth is not an issue here.
  • Auxiliary space: O(V): The extra space is needed for the 2 stacks used.

Please refer complete article on Topological Sorting for more details. 


Next Article
All Topological Sorts of a Directed Acyclic Graph

K

kartik
Improve
Article Tags :
  • Python
  • python sorting-exercises
Practice Tags :
  • python

Similar Reads

    Topological Sorting
    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],
    10 min read
    Kahn's algorithm for Topological Sorting
    Given a Directed Acyclic Graph having V vertices and E edges, your task is to find any Topological Sorted order of the graph.Topological Sorted order: It is a linear ordering of vertices such that for every directed edge u -> v, where vertex u comes before v in the ordering.Example:Input: V=6 , E
    9 min read

    Topological Sort in different languages

    C Program for Topological Sorting
    A fundamental procedure in computer science called topological sorting is used to arrange the nodes in a directed network. This sorting method makes sure that vertex u is placed before vertex v in the sorted order for each directed edge (u, v). Numerous fields, including work scheduling, project pla
    4 min read
    C++ Program for Topological Sorting
    Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. For example, a topological sorting of the following graph is
    3 min read
    Java Program for Topological Sorting
    Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. For example, a topological sorting of the following graph is
    3 min read
    Topological Sorting in Python
    Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.Example: Input: Graph : ExampleOutput: 5 4 2 3 1 0Explanation
    6 min read

    Problems based on Topological Sort

    All Topological Sorts of a Directed Acyclic Graph
    Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. Given a DAG, print all topological sorts of the graph. For e
    11 min read
    Detect cycle in Directed Graph using Topological Sort
    Given a Directed Graph consisting of N vertices and M edges and a set of Edges[][], the task is to check whether the graph contains a cycle or not using Topological sort. Topological sort of directed graph is a linear ordering of its vertices such that, for every directed edge U -> V from vertex
    9 min read
    Lexicographically Smallest Topological Ordering
    Given a directed graph with N vertices and M edges that may contain cycles, the task is to find the lexicographically smallest topological ordering of the graph if it exists otherwise print -1 (if the graph has cycles). Lexicographically smallest topological ordering means that if two vertices in a
    8 min read
    Topological Sort of a graph using departure time of vertex
    Given a Directed Acyclic Graph (DAG), find Topological Sort of the graph. Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph
    9 min read
    Smallest set of vertices to visit all nodes of the given Graph
    Given a directed acyclic graph of N nodes, the task is to find the smallest set of vertices from which the complete graph can be visited.Examples: Input: Graph in the image belowOutput: 0 4Explanation: From vertex 0, the set of nodes that can be visited is {0 ,1}. Similarly, from vertex 4, {4, 3, 2}
    12 min read
    Minimum time taken by each job to be completed given by a Directed Acyclic Graph
    Given a Directed Acyclic Graph having V vertices and E edges, where each edge {U, V} represents the Jobs U and V such that Job V can only be started only after completion of Job U. The task is to determine the minimum time taken by each job to be completed where each Job takes unit time to get compl
    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