⚡️ Speed up method PathFinder.find_shortest_path
by 246%
#65
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 246% (2.46x) speedup for
PathFinder.find_shortest_path
insrc/dsa/various.py
⏱️ Runtime :
2.74 milliseconds
→792 microseconds
(best of903
runs)📝 Explanation and details
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 usescollections.deque
withpopleft()
, 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:
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.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-PathFinder.find_shortest_path-mdpcrce2
and push.