From f9f8f76a30b7a58ffc564592cc18b15fb21138ea Mon Sep 17 00:00:00 2001 From: dharsh03rs-cpu Date: Sun, 23 Aug 2026 09:13:55 +0530 Subject: [PATCH] Fix Kahn's algorithm --- graphs/kahns_algorithm_topo.py | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/graphs/kahns_algorithm_topo.py b/graphs/kahns_algorithm_topo.py index c956cf9f48fd..bbf266dd8a10 100644 --- a/graphs/kahns_algorithm_topo.py +++ b/graphs/kahns_algorithm_topo.py @@ -1,3 +1,6 @@ +from collections import deque + + def topological_sort(graph: dict[int, list[int]]) -> list[int] | None: """ Perform topological sorting of a Directed Acyclic Graph (DAG) @@ -21,10 +24,18 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None: >>> graph_with_cycle = {0: [1], 1: [2], 2: [0]} >>> topological_sort(graph_with_cycle) + + >>> sparse_graph = {10: [20], 20: []} + >>> topological_sort(sparse_graph) + [10, 20] + + >>> sparse_graph = {10: [20, 30], 20: [40], 30: [40], 40: []} + >>> topological_sort(sparse_graph) + [10, 20, 30, 40] """ - indegree = [0] * len(graph) - queue = [] + indegree = dict.fromkeys(graph, 0) + queue = deque() topo_order = [] processed_vertices_count = 0 @@ -34,13 +45,13 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None: indegree[i] += 1 # Add all vertices with 0 indegree to the queue - for i in range(len(indegree)): - if indegree[i] == 0: - queue.append(i) + for vertex in graph: + if indegree[vertex] == 0: + queue.append(vertex) # Perform BFS while queue: - vertex = queue.pop(0) + vertex = queue.popleft() processed_vertices_count += 1 topo_order.append(vertex)