Commit 69a4d71
authored
⚡️ Speed up method
The optimized code achieves a 245% speedup through two key algorithmic improvements:
**1. Replaced list-based queue with deque for O(1) operations**
The original code used `queue.pop(0)` on a list, which is O(n) because it shifts all remaining elements. The line profiler shows this operation taking 15.4% of total time (2.327ms out of 15.129ms). The optimized version uses `collections.deque` with `popleft()`, which is O(1). This change alone eliminates the most expensive operation in the BFS traversal.
**2. Eliminated path copying with parent tracking**
The original code maintained complete paths by copying and extending them (`new_path = list(path)` + `new_path.append(neighbor)`), taking 19.7% of total time (12.6% + 7.1%). With thousands of nodes visited, this creates substantial memory allocation overhead. The optimized version stores only parent pointers in a dictionary and reconstructs the path once at the end, reducing both time and space complexity.
**Performance characteristics by test case type:**
- **Large linear graphs (1000+ nodes)**: Show the most dramatic improvement (400-433% faster) because they maximize the impact of both optimizations - many queue operations and long paths to copy
- **Small graphs (2-5 nodes)**: Actually perform 17-50% slower due to the overhead of importing deque and managing the parent dictionary, but the absolute difference is negligible (microseconds)
- **Dense/branching graphs**: Show moderate improvements (10-96% faster) as they benefit from reduced queue overhead but have shorter average path lengths
- **Disconnected graphs**: Benefit significantly (286% faster) when no path exists, as the BFS explores many nodes before terminating
The optimization transforms the algorithm from O(V²) time complexity (due to path copying) to O(V + E), making it scale much better for larger graphs while maintaining identical BFS shortest-path semantics.PathFinder.find_shortest_path by 246%1 parent 9b951ff commit 69a4d71
1 file changed
+12
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
| 2 | + | |
2 | 3 | | |
3 | 4 | | |
4 | 5 | | |
| |||
96 | 97 | | |
97 | 98 | | |
98 | 99 | | |
99 | | - | |
| 100 | + | |
100 | 101 | | |
| 102 | + | |
101 | 103 | | |
102 | 104 | | |
103 | | - | |
104 | | - | |
| 105 | + | |
105 | 106 | | |
106 | 107 | | |
107 | | - | |
| 108 | + | |
| 109 | + | |
| 110 | + | |
| 111 | + | |
| 112 | + | |
| 113 | + | |
108 | 114 | | |
109 | 115 | | |
110 | 116 | | |
111 | 117 | | |
112 | | - | |
113 | | - | |
114 | | - | |
| 118 | + | |
| 119 | + | |
115 | 120 | | |
116 | 121 | | |
0 commit comments