⚡️ Speed up function find_last_node by 6,873%
#257
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.
📄 6,873% (68.73x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
23.6 milliseconds→339 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 6873% speedup by replacing an O(n×m) nested loop with an O(m+n) set-based lookup, where n is the number of nodes and m is the number of edges.
Key Optimization
Original approach: For each node, the code iterates through ALL edges to check if that node is a source:
This creates n×m comparisons in the worst case.
Optimized approach: Build a set of all source IDs once, then use O(1) membership tests:
This reduces complexity from O(n×m) to O(m+n).
Performance Impact by Scale
The speedup grows dramatically with input size:
This is because the quadratic behavior of the original code becomes increasingly expensive as the number of nodes and edges grows.
Edge Cases Preserved
The optimization maintains original behavior through careful handling:
Empty edges: When
edges = [], the setsourcesis empty. The code returns the first node without accessingn["id"], matching the original's lazy evaluation viaall()on an empty sequence.Unhashable sources: A try-except catches
TypeErrorif edge sources aren't hashable (rare but possible), falling back to the original logic.Missing keys: Both versions raise
KeyErrorwhen nodes lack 'id' keys or edges lack 'source' keys, but only when those keys are actually accessed.When This Optimization Matters Most
Based on test results and typical graph algorithm usage, this optimization is particularly valuable when:
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mkm6kvu3and push.