Skip to content

Commit c6c19d6

Browse files
author
deepshekhardas
committed
fix(graphs): use deque and dict indegree for sparse vertex IDs
1 parent c0db072 commit c6c19d6

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

graphs/kahns_algorithm_topo.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,27 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
2323
>>> topological_sort(graph_with_cycle)
2424
"""
2525

26-
indegree = [0] * len(graph)
27-
queue = []
26+
from collections import deque
27+
28+
# Use dict for indegree to support sparse/non-contiguous vertex IDs
29+
indegree: dict[int, int] = {v: 0 for v in graph}
30+
queue: deque[int] = deque()
2831
topo_order = []
2932
processed_vertices_count = 0
3033

3134
# Calculate the indegree of each vertex
3235
for values in graph.values():
3336
for i in values:
34-
indegree[i] += 1
37+
indegree[i] = indegree.get(i, 0) + 1
3538

3639
# Add all vertices with 0 indegree to the queue
37-
for i in range(len(indegree)):
38-
if indegree[i] == 0:
39-
queue.append(i)
40+
for v, deg in indegree.items():
41+
if deg == 0:
42+
queue.append(v)
4043

4144
# Perform BFS
4245
while queue:
43-
vertex = queue.pop(0)
46+
vertex = queue.popleft()
4447
processed_vertices_count += 1
4548
topo_order.append(vertex)
4649

0 commit comments

Comments
 (0)