Skip to content
83 changes: 83 additions & 0 deletions data_structures/sort/topological_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""

Check failure on line 1 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (INP001)

data_structures/sort/topological_sort.py:1:1: INP001 File `data_structures/sort/topological_sort.py` is part of an implicit namespace package. Add an `__init__.py`.
Topological Sort implementation using:
1. DFS-based approach
2. Kahn's Algorithm (BFS-based approach)

Topological sorting is applicable only for Directed Acyclic Graphs (DAGs).

Reference:
https://en.wikipedia.org/wiki/Topological_sorting
"""

from collections import deque
from typing import List

Check failure on line 13 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

data_structures/sort/topological_sort.py:13:1: UP035 `typing.List` is deprecated, use `list` instead


def topological_sort_dfs(vertices: int, edges: List[List[int]]) -> List[int]:

Check failure on line 16 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:16:68: UP006 Use `list` instead of `List` for type annotation

Check failure on line 16 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:16:53: UP006 Use `list` instead of `List` for type annotation

Check failure on line 16 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:16:48: UP006 Use `list` instead of `List` for type annotation
"""
Perform topological sort using DFS.

>>> order = topological_sort_dfs(
... 6, [[5, 2], [5, 0], [4, 0], [4, 1], [2, 3], [3, 1]]
... )
>>> len(order) == 6
True
"""
graph: List[List[int]] = [[] for _ in range(vertices)]

Check failure on line 26 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:26:17: UP006 Use `list` instead of `List` for type annotation

Check failure on line 26 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:26:12: UP006 Use `list` instead of `List` for type annotation
for u, v in edges:
graph[u].append(v)

visited = [0] * vertices
result: List[int] = []

Check failure on line 31 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:31:13: UP006 Use `list` instead of `List` for type annotation

def dfs(node: int) -> None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file data_structures/sort/topological_sort.py, please provide doctest for the function dfs

if visited[node] == 1:
raise ValueError("Graph contains a cycle")
if visited[node] == 2:
return

visited[node] = 1
for neighbor in graph[node]:
dfs(neighbor)
visited[node] = 2
result.append(node)

for vertex in range(vertices):
if visited[vertex] == 0:
dfs(vertex)

return result[::-1]


def topological_sort_kahn(vertices: int, edges: List[List[int]]) -> List[int]:

Check failure on line 52 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:52:54: UP006 Use `list` instead of `List` for type annotation

Check failure on line 52 in data_structures/sort/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/sort/topological_sort.py:52:49: UP006 Use `list` instead of `List` for type annotation
"""
Perform topological sort using Kahn's Algorithm.

>>> order = topological_sort_kahn(
... 6, [[5, 2], [5, 0], [4, 0], [4, 1], [2, 3], [3, 1]]
... )
>>> len(order) == 6
True
"""
graph: List[List[int]] = [[] for _ in range(vertices)]
in_degree = [0] * vertices

for u, v in edges:
graph[u].append(v)
in_degree[v] += 1

queue = deque(i for i in range(vertices) if in_degree[i] == 0)
topo_order: List[int] = []

while queue:
node = queue.popleft()
topo_order.append(node)
for neighbor in graph[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)

if len(topo_order) != vertices:
raise ValueError("Graph contains a cycle")

return topo_order