Tutorialspoint
Problem
Solution
Submissions

Topological Sort

Certification: Advanced Level Accuracy: 66.67% Submissions: 3 Points: 15

Write a Python function that performs topological sorting on a Directed Acyclic Graph (DAG). Topological sorting is a linear ordering of vertices such that for every directed edge (u, v), vertex u comes before v in the ordering.

Example 1
  • Input: {0: [1, 2], 1: [3], 2: [3], 3: [], 4: [0, 1]}
  • Output: [4, 0, 2, 1, 3]
  • Explanation:
    • Step 1: Build the graph from the adjacency list.
    • Step 2: Perform DFS with visited tracking.
    • Step 3: Return the topological order [4, 0, 2, 1, 3].
Example 2
  • Input: {0: [1, 2], 1: [], 2: [3], 3: []}
  • Output: [0, 2, 3, 1]
  • Explanation:
    • Step 1: Build the graph from the adjacency list.
    • Step 2: Perform DFS with visited tracking.
    • Step 3: Return the topological order [0, 2, 3, 1].
Constraints
  • 1 ≤ number of vertices ≤ 10^5
  • 0 ≤ number of edges ≤ 10^6
  • Graph is represented as an adjacency list
  • Graph is a DAG (no cycles)
  • Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges
  • Space Complexity: O(V)
GraphAlgorithmsGoogleEY
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Depth-First Search (DFS) to explore vertices
  • Keep track of visited vertices and vertices currently in the recursion stack
  • Use a stack to store vertices in the post-order of DFS
  • Check for cycles using a "visited" and "in_stack" array
  • Reverse the final stack to get the topological order

Steps to solve by this approach:

 Step 1: Calculate the in-degree (number of incoming edges) for each node in the graph.

 Step 2: Initialize a queue with all nodes that have zero in-degree.
 Step 3: Process nodes from the queue, adding them to the topological order.
 Step 4: For each processed node, decrease the in-degree of all its neighbors.
 Step 5: If a neighbor's in-degree becomes zero, add it to the queue.
 Step 6: Continue until the queue is empty and verify that all nodes were processed.
 Step 7: Return the topological order or empty list if a cycle is detected.

Submitted Code :