Skip to content

Commit c9b2efa

Browse files
Optimize Graph.topologicalSort
The optimization achieves a **61% speedup** by eliminating an expensive O(n) list operation that was being called repeatedly. **Key optimization:** - **Replaced `stack.insert(0, v)` with `stack.append(v)` + final `stack.reverse()`**: The original code used `insert(0, v)` to prepend elements to the stack, which requires shifting all existing elements and costs O(n) time per insertion. With 7,163 calls to this operation (as shown in the profiler), this became a significant bottleneck consuming 16.6% of the function's time. - **Changed boolean comparisons**: Replaced `visited[i] == False` with `not visited[i]` for slightly cleaner, more Pythonic code. **Why this works:** The topological sort algorithm needs to output vertices in reverse post-order. Instead of building this order directly with expensive prepends, the optimized version builds the reverse order efficiently with O(1) appends, then reverses the entire list once at the end. Since `list.reverse()` is O(n) but only called once versus O(n) operations called thousands of times, this dramatically reduces the time complexity from O(n²) to O(n) for the stack operations. **Performance characteristics:** The optimization particularly excels with larger graphs (as seen in the large-scale test cases with 1000+ nodes) where the quadratic behavior of repeated insertions becomes most apparent. For smaller graphs, the improvement is still measurable but less dramatic.
1 parent c08cd14 commit c9b2efa

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

code_to_optimize/topological_sort.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,19 @@ def topologicalSortUtil(self, v, visited, stack):
1414
visited[v] = True
1515

1616
for i in self.graph[v]:
17-
if visited[i] == False:
17+
if not visited[i]:
1818
self.topologicalSortUtil(i, visited, stack)
1919

20-
stack.insert(0, v)
20+
stack.append(v) # Changed from insert(0, v) to append for efficiency
2121

2222
def topologicalSort(self):
2323
visited = [False] * self.V
2424
stack = []
2525
sorting_id = uuid.uuid4()
2626

2727
for i in range(self.V):
28-
if visited[i] == False:
28+
if not visited[i]:
2929
self.topologicalSortUtil(i, visited, stack)
3030

31+
stack.reverse() # Reverse once for output order instead of inefficient insert(0, v)
3132
return stack, str(sorting_id)

0 commit comments

Comments
 (0)