⚡️ Speed up function graph_traversal by 916%
#147
Closed
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.
📄 916% (9.16x) speedup for
graph_traversalinsrc/dsa/various.py⏱️ Runtime :
9.57 milliseconds→942 microseconds(best of5runs)📝 Explanation and details
The optimized code achieves a 915% speedup by replacing the O(n) list lookup for visited nodes with an O(1) set lookup. The key changes are:
visited_set = set()for O(1) membership testingif n in visited_setinstead ofif n in visitedvisited_set.add(n)alongsidevisited.append(n)to preserve the original return formatgraph.get(n, [])tograph.get(n, ())using an empty tuple instead of listThe performance improvement comes from eliminating the expensive O(n) list search operation that occurs on every node visit. In the original code, checking
if n in visitedrequires scanning through the entire visited list, which becomes increasingly expensive as more nodes are traversed.Test case analysis shows the optimization is most effective for:
The optimization maintains identical functionality and return values while dramatically improving performance for any graph traversal involving more than a few nodes.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_fb1xiyqb/tmp0rb6oxxp/test_concolic_coverage.py::test_graph_traversalTo edit these changes
git checkout codeflash/optimize-graph_traversal-mha62sr2and push.