Commit 5390c13
authored
Optimize Graph.topologicalSort
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.1 parent be86bdc commit 5390c13
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