DSA — Topological Sort
What is Topological Sort?
Linear ordering of vertices such that for every directed edge u→v, u comes before v.
# DFS-based
def topological_sort(graph):
visited = set()
stack = []
def dfs(vertex):
visited.add(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
dfs(neighbor)
stack.append(vertex)
for vertex in graph:
if vertex not in visited:
dfs(vertex)
return stack[::-1]
# Kahn's algorithm (BFS-based)
def topological_sort_kahn(graph, in_degree):
queue = [v for v in graph if in_degree[v] == 0]
result = []
while queue:
vertex = queue.pop(0)
result.append(vertex)
for neighbor in graph[vertex]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return result
Time Complexity
| Method | Complexity |
|---|---|
| DFS | O(V + E) |
| Kahn's | O(V + E) |
Applications
- Task scheduling
- Build systems
- Course prerequisites
- Dependency resolution
Mini Practice
- Implement topological sort
- Detect cycles using it
- Schedule tasks with dependencies
- Compare DFS and BFS approaches
Up Next
Continue with Dynamic Programming — optimization technique.
Related Topics
Frequently Asked Questions about Topological Sort
What is Topological Sort in DSA?
Topological Sort is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Topological Sort?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Topological Sort.
Why is Topological Sort important in DSA?
Topological Sort is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.