⚡️ Speed up function find_last_node by 16,584%
#195
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.
📄 16,584% (165.84x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
65.2 milliseconds→391 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 166x speedup by eliminating redundant nested iterations and replacing them with efficient set-based lookups.
Key Optimizations
1. Early Return for Empty Edges
The optimization adds a fast-path check: if there are no edges, return the first node immediately. This avoids any iteration overhead for disconnected graphs, providing 157-314% speedup on such cases.
2. Set-Based Source Lookup
The critical optimization replaces the nested
all(e["source"] != n["id"] for e in edges)check with:sources = {e["source"] for e in edges}n["id"] not in sourcesThis transforms the algorithm from O(nodes × edges) to O(nodes + edges) complexity.
Why This Works
In the original code, for each node, it iterates through all edges to check if that node is a source. With 1000 nodes and 1000 edges, this performs up to 1 million comparisons.
The optimized version builds the source set once (1000 operations), then does constant-time set lookups for each node (1000 × O(1)), totaling ~2000 operations—a 500x reduction in work.
Performance Impact by Test Type
The optimization particularly excels when there are many nodes and edges, as it eliminates the quadratic blowup that occurs in the nested iteration pattern of the original implementation.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mjhqpyu3and push.