⚡️ Speed up function find_last_node by 19,810%#286
Open
codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
Open
⚡️ Speed up function find_last_node by 19,810%#286codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
find_last_node by 19,810%#286codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
Conversation
The optimized code achieves a **198x runtime speedup** (from 130ms to 655μs) by replacing an O(N×M) nested iteration with an O(N+M) set-based lookup algorithm.
**Key Optimization:**
The original implementation uses a nested generator expression that checks `all(e["source"] != n["id"] for e in edges)` for each node. This means for every node, it must iterate through *all* edges to verify none of them have that node as a source. With N nodes and M edges, this becomes O(N×M) comparisons.
The optimized version first detects whether `edges` is re-iterable (like a list) or a single-pass iterator (like a generator). For re-iterable collections—the common case—it **precomputes a set of all source IDs** in O(M) time using `sources = {e["source"] for e in edges}`. Then it checks each node's ID against this set in O(1) time, making the overall complexity O(N+M).
**Why This Works:**
Python sets provide O(1) average-case membership testing via hash lookups. By converting the M edge sources into a set once, each of the N node checks becomes a fast hash lookup instead of iterating through all M edges. The performance gain is dramatic when both N and M are large.
**Test Case Performance:**
The speedup is most pronounced in tests with large inputs:
- `test_large_chain_of_1000_nodes_returns_last_node`: 34.8ms → 114μs (303x faster)
- `test_very_large_graph_1000_nodes_complete_chain`: 26.7ms → 46.4μs (573x faster)
- `test_large_linear_chain_500_nodes`: 6.80ms → 25.0μs (270x faster)
Even small inputs benefit substantially (2-4x speedup) due to reduced constant-factor overhead from avoiding nested iteration.
**Iterator Preservation:**
The optimization correctly preserves behavior for single-pass iterators by detecting them with `if it is edges` and falling back to sequential consumption that mirrors the original's iterator advancement pattern, ensuring functional correctness across all input types.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
📄 19,810% (198.10x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
130 milliseconds→655 microseconds(best of155runs)📝 Explanation and details
The optimized code achieves a 198x runtime speedup (from 130ms to 655μs) by replacing an O(N×M) nested iteration with an O(N+M) set-based lookup algorithm.
Key Optimization:
The original implementation uses a nested generator expression that checks
all(e["source"] != n["id"] for e in edges)for each node. This means for every node, it must iterate through all edges to verify none of them have that node as a source. With N nodes and M edges, this becomes O(N×M) comparisons.The optimized version first detects whether
edgesis re-iterable (like a list) or a single-pass iterator (like a generator). For re-iterable collections—the common case—it precomputes a set of all source IDs in O(M) time usingsources = {e["source"] for e in edges}. Then it checks each node's ID against this set in O(1) time, making the overall complexity O(N+M).Why This Works:
Python sets provide O(1) average-case membership testing via hash lookups. By converting the M edge sources into a set once, each of the N node checks becomes a fast hash lookup instead of iterating through all M edges. The performance gain is dramatic when both N and M are large.
Test Case Performance:
The speedup is most pronounced in tests with large inputs:
test_large_chain_of_1000_nodes_returns_last_node: 34.8ms → 114μs (303x faster)test_very_large_graph_1000_nodes_complete_chain: 26.7ms → 46.4μs (573x faster)test_large_linear_chain_500_nodes: 6.80ms → 25.0μs (270x faster)Even small inputs benefit substantially (2-4x speedup) due to reduced constant-factor overhead from avoiding nested iteration.
Iterator Preservation:
The optimization correctly preserves behavior for single-pass iterators by detecting them with
if it is edgesand falling back to sequential consumption that mirrors the original's iterator advancement pattern, ensuring functional correctness across all input types.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mlurhqw4and push.