From 4052aff64e2ac961d1ca9368caab76530d9a2558 Mon Sep 17 00:00:00 2001 From: sudo-ai-git Date: Thu, 27 Aug 2026 23:52:46 -0500 Subject: [PATCH] perf(graphs): use deque.popleft() for O(1) queue ops in Kahn's topological sort --- graphs/kahns_algorithm_topo.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/graphs/kahns_algorithm_topo.py b/graphs/kahns_algorithm_topo.py index c956cf9f48fd..ba7546c36ddc 100644 --- a/graphs/kahns_algorithm_topo.py +++ b/graphs/kahns_algorithm_topo.py @@ -23,8 +23,10 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None: >>> topological_sort(graph_with_cycle) """ + from collections import deque + indegree = [0] * len(graph) - queue = [] + queue = deque() topo_order = [] processed_vertices_count = 0 @@ -40,7 +42,7 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None: # Perform BFS while queue: - vertex = queue.pop(0) + vertex = queue.popleft() processed_vertices_count += 1 topo_order.append(vertex)