Commit 5d9297f
authored
Optimize Graph.topologicalSort
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.1 parent bb7b2c9 commit 5d9297f
1 file changed
Lines changed: 6 additions & 4 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
| 3 | + | |
3 | 4 | | |
4 | 5 | | |
5 | 6 | | |
| |||
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 | | |
| 32 | + | |
31 | 33 | | |
0 commit comments