⚡️ Speed up function find_last_node by 4,704%
#267
+26
−1
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.
📄 4,704% (47.04x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
11.5 milliseconds→238 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 4703% speedup (from 11.5ms to 238μs) by replacing an O(N×M) nested loop with O(N+M) operations using a set-based lookup strategy.
Key Optimization:
The original code uses a nested generator expression: for each node, it iterates through ALL edges to check if that node is a source. This creates O(N×M) comparisons where N is the number of nodes and M is the number of edges.
The optimized code:
sources = {e["source"] for e in edges}- O(M) timeif n["id"] not in sources- O(N) timeWhy This Works:
Python sets use hash tables, making membership checks nearly instantaneous regardless of set size. Instead of comparing each node against every edge repeatedly, we build the set once and perform fast lookups.
Performance Impact by Test Case:
Edge Case Preservation:
The code carefully handles the original behavior where nodes without an 'id' key don't raise KeyError when edges is empty (the
all()short-circuits without evaluatingn["id"]). The optimized version checksif sources:before accessingn["id"], preserving this quirk.Conclusion:
This optimization transforms a quadratic algorithm into a linear one, making it dramatically faster for realistic graph sizes (100+ nodes) while maintaining identical behavior for all edge cases.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
📊 Performance Profile
View detailed line-by-line performance analysis
To edit these changes
git checkout codeflash/optimize-find_last_node-ml2jdrqxand push.