⚡️ Speed up function find_last_node by 21,941%
#225
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.
📄 21,941% (219.41x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
66.8 milliseconds→303 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 220x speedup by eliminating a costly nested loop through a simple algorithmic improvement.
Key Optimization:
The original implementation uses
all(e["source"] != n["id"] for e in edges)for each node, which creates an O(N × E) complexity where N is the number of nodes and E is the number of edges. For every node, it iterates through all edges to check if that node appears as a source.The optimized version pre-computes a set of all source node IDs once:
sources = {e["source"] for e in edges}. Then it uses O(1) set membership testing (n["id"] not in sources) for each node, reducing the overall complexity to O(N + E).Performance Impact:
The speedup is most dramatic when the graph has many edges:
For small graphs (2-4 nodes), the optimization still provides 50-80% speedup. Even the empty graph case shows only minimal overhead (14% slower), which is negligible given the microsecond timescale.
Why It's Faster:
Set construction and lookup in Python are highly optimized hash table operations with O(1) average-case complexity. The original approach repeatedly scans the entire edges list, which becomes prohibitively expensive as the graph grows. The optimization trades a small upfront cost (building the set) for massive savings during the node iteration.
This optimization is universally beneficial across all test cases involving non-trivial edge counts, making it an excellent candidate for merging.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mjj7rfyxand push.