codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

50 / 65 topics
49Graph Coloring50Topological Sorting51Strongly Connected Components52Eulerian Cycles and Paths53Hamiltonian Cycles
Tutorials/Data Structures & Algorithms/Topological Sorting
🧮Data Structures & Algorithms

Topological Sorting

Updated 2026-05-15
10 min read

Topological Sorting

Introduction

In the realm of computer science, topological sorting is a linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge \( u \rightarrow v \), vertex \( u \) comes before \( v \) in the ordering. This concept is fundamental in various applications, including scheduling tasks with dependencies, resolving software package dependencies, and more.

Concept

Topological sorting can be achieved using two main algorithms:

  1. Depth-First Search (DFS): By performing a DFS on the graph, we can assign a timestamp to each vertex when it finishes processing. The vertices are then sorted based on these timestamps in descending order.
  2. Kahn's Algorithm: This algorithm uses the concept of in-degrees (number of incoming edges) of vertices. It repeatedly removes vertices with an in-degree of 0 and decreases the in-degree of its neighbors.

Both methods ensure that all directed edges respect the topological order.

Examples

Let's explore both algorithms through practical examples.

Depth-First Search (DFS)

Here is a Python implementation using DFS:

Python
1def topological_sort_dfs(graph):
2 def dfs_util(v, visited, stack):
3 visited[v] = True
4 for i in graph[v]:
5 if not visited[i]:
6 dfs_util(i, visited, stack)
7 stack.insert(0, v)
8
9 visited = {node: False for node in graph}
10 stack = []
11
12 for node in graph:
13 if not visited[node]:
14 dfs_util(node, visited, stack)
15
16 return stack
17
18# Example usage
19graph_dfs = {
20 'A': ['C'],
21 'B': ['C', 'D'],
22 'C': ['E'],
23 'D': ['F'],
24 'E': [],
25 'F': []
26}
27
28print("Topological Sort using DFS:", topological_sort_dfs(graph_dfs))
Output
Topological Sort using DFS: ['A', 'B', 'D', 'C', 'E', 'F']

Kahn's Algorithm

Here is a Python implementation using Kahn's algorithm:

Python
1from collections import deque
2
3def topological_sort_kahn(graph):
4 in_degree = {node: 0 for node in graph}
5 for u in graph:
6 for v in graph[u]:
7 in_degree[v] += 1
8
9 queue = deque([u for u in graph if in_degree[u] == 0])
10 topo_order = []
11
12 while queue:
13 u = queue.popleft()
14 topo_order.append(u)
15 for v in graph[u]:
16 in_degree[v] -= 1
17 if in_degree[v] == 0:
18 queue.append(v)
19
20 return topo_order
21
22# Example usage
23graph_kahn = {
24 'A': ['C'],
25 'B': ['C', 'D'],
26 'C': ['E'],
27 'D': ['F'],
28 'E': [],
29 'F': []
30}
31
32print("Topological Sort using Kahn's Algorithm:", topological_sort_kahn(graph_kahn))
Output
Topological Sort using Kahn's Algorithm: ['A', 'B', 'D', 'C', 'E', 'F']

What's Next?

After mastering topological sorting, you can delve into more advanced topics such as Graph Connectivity. Understanding how to determine if a graph is connected or finding connected components will provide deeper insights into the structure and properties of graphs.


PreviousGraph ColoringNext Strongly Connected Components

Recommended Gear

Graph ColoringStrongly Connected Components