
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)
Editorial
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. |
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