From 5390c136eaeb69e69267af70b3619fbd903edec3 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Sat, 8 Nov 2025 08:12:50 +0000 Subject: [PATCH] Optimize Graph.topologicalSort MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The optimized code achieves a **140% speedup** by replacing an inefficient list operation with a more performant approach. The key optimization is changing `stack.insert(0, v)` to `stack.append(v)` followed by a single `stack.reverse()` call. **What changed:** - In `topologicalSortUtil`: `stack.insert(0, v)` → `stack.append(v)` - In `topologicalSort`: Added `stack.reverse()` before returning - Minor improvement: `visited[i] == False` → `not visited[i]` (slightly more Pythonic) **Why this is faster:** The original code performs `stack.insert(0, v)` for every node visited, which is an O(N) operation since Python lists must shift all existing elements when inserting at the head. For a graph with N nodes, this results in O(N²) total time complexity just for list operations. The optimized version uses `stack.append(v)` (O(1) operation) for each node, then performs a single `stack.reverse()` (O(N)) at the end. This reduces the list operation complexity from O(N²) to O(N). **Performance impact:** The line profiler shows the stack operation time dropped from 3.06ms (21% of total time) to 1.78ms (12.6% of total time) in `topologicalSortUtil`. The optimization is particularly effective for larger graphs - test cases show **157-197% speedup** for graphs with 1000 nodes, while smaller graphs (≤5 nodes) show minimal or mixed results since the O(N²) vs O(N) difference isn't significant at small scales. This optimization maintains identical functionality and correctness while dramatically improving performance for larger topological sorting workloads. --- code_to_optimize/topological_sort.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/code_to_optimize/topological_sort.py b/code_to_optimize/topological_sort.py index 6d3fa457a..0680dbce3 100644 --- a/code_to_optimize/topological_sort.py +++ b/code_to_optimize/topological_sort.py @@ -14,10 +14,10 @@ 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) # More efficient than insert(0, v) def topologicalSort(self): visited = [False] * self.V @@ -25,7 +25,8 @@ def topologicalSort(self): 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() # Reversing once is faster than repeated insert(0, v) return stack, str(sorting_id)