From 5d9297f6452c889aa599ce6feb0b50287456ab3a Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Thu, 13 Nov 2025 01:48:49 +0000 Subject: [PATCH] Optimize Graph.topologicalSort MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The optimization achieves a **28% speedup** by replacing the inefficient `stack.insert(0, v)` operation with `stack.append(v)` followed by a single `stack.reverse()` at the end. **Key optimization**: The original code used `stack.insert(0, v)` in `topologicalSortUtil`, which is an O(N) operation because it requires shifting all existing elements in the list. This happened for every node processed during the DFS traversal. The optimized version uses `stack.append(v)` (O(1)) and reverses the entire stack once at the end (O(N)). **Why this is faster**: For a graph with N nodes, the original approach performs N insertions at index 0, resulting in O(N²) time complexity for stack operations alone. The optimized approach performs N constant-time appends plus one O(N) reverse, reducing the stack operations to O(N) total. **Performance impact analysis**: The line profiler shows the critical improvement - the `stack.insert(0, v)` line took 3.885e+06 nanoseconds (347.3 ns per hit) in the original, while `stack.append(v)` takes only 2.802e+06 nanoseconds (250.5 ns per hit) in the optimized version. The single `stack.reverse()` operation is negligible at 17,000 nanoseconds total. **Test case benefits**: The optimization shows increasing benefits with graph size: - Small graphs (3 nodes): Minimal improvement (~1-8%) - Large sparse graphs (1000 nodes): ~15-18% improvement - Dense graphs (100 nodes with many edges): **25.8% improvement** This demonstrates that the optimization scales well with problem size, making it particularly valuable for larger topological sorting tasks. --- code_to_optimize/topological_sort.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/code_to_optimize/topological_sort.py b/code_to_optimize/topological_sort.py index 6d3fa457a..c433ae528 100644 --- a/code_to_optimize/topological_sort.py +++ b/code_to_optimize/topological_sort.py @@ -1,5 +1,6 @@ import uuid from collections import defaultdict +from typing import List class Graph: @@ -14,18 +15,19 @@ def topologicalSortUtil(self, v, visited, stack): visited[v] = True for i in self.graph[v]: - if visited[i] == False: + if not visited[i]: self.topologicalSortUtil(i, visited, stack) - stack.insert(0, v) + stack.append(v) # Appending is O(1); we'll reverse later def topologicalSort(self): visited = [False] * self.V - stack = [] + stack: List[int] = [] sorting_id = uuid.uuid4() for i in range(self.V): - if visited[i] == False: + if not visited[i]: self.topologicalSortUtil(i, visited, stack) + stack.reverse() # Reverse once at the end for O(N) instead of repeated O(N) .insert(0, ...) return stack, str(sorting_id)