Commit c9b2efa
authored
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
1 file changed
+4
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
14 | 14 | | |
15 | 15 | | |
16 | 16 | | |
17 | | - | |
| 17 | + | |
18 | 18 | | |
19 | 19 | | |
20 | | - | |
| 20 | + | |
21 | 21 | | |
22 | 22 | | |
23 | 23 | | |
24 | 24 | | |
25 | 25 | | |
26 | 26 | | |
27 | 27 | | |
28 | | - | |
| 28 | + | |
29 | 29 | | |
30 | 30 | | |
| 31 | + | |
31 | 32 | | |
0 commit comments