⚡️ Speed up function graph_traversal
by 1,193%
#61
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.
📄 1,193% (11.93x) speedup for
graph_traversal
insrc/dsa/various.py
⏱️ Runtime :
5.37 milliseconds
→416 microseconds
(best of15
runs)📝 Explanation and details
The optimized code achieves a ~12x speedup by replacing a list-based visited tracking mechanism with a set-based approach, addressing the core performance bottleneck in graph traversal.
Key Optimization Applied:
set()
for O(1) membership checking (visited
) and a separatelist
for maintaining traversal order (result
)graph.get(n, [])
tograph.get(n, {})
to match the expected dict typeWhy This Creates Massive Speedup:
The original code's
if n in visited
operation on a list has O(n) time complexity - it must scan through the entire list linearly. As the graph grows, each membership check becomes progressively slower. The optimized version usesif n in visited
on a set, which is O(1) average case due to hash table lookups.Performance Impact by Graph Size:
Best Use Cases:
The optimization excels for:
The annotation test results clearly show this pattern - small test cases are slightly slower due to set initialization overhead, while large-scale tests show exponential performance gains as the visited collection grows.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-graph_traversal-mdpca1f5
and push.