⚡️ Speed up function find_last_node by 4,605%#276
Closed
codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Closed
⚡️ Speed up function find_last_node by 4,605%#276codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
find_last_node by 4,605%#276codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Conversation
The optimized code achieves a **46x speedup** (4605% improvement) by eliminating the quadratic O(N×M) complexity of the original implementation and replacing it with a linear O(N+M) approach.
**Key Optimization:**
The original code uses nested iteration via `all(e["source"] != n["id"] for e in edges)`, which re-scans the entire `edges` collection for every node. This creates O(N×M) time complexity where N is the number of nodes and M is the number of edges.
The optimized version introduces a smart branching strategy:
1. **For re-iterable collections** (lists, tuples - the common case): It builds a set of source IDs in one pass (`sources = {e["source"] for e in edges}`), then checks membership with O(1) lookups. This reduces complexity to O(N+M) with minimal O(M) memory overhead.
2. **For single-pass iterators**: It preserves the original consumption semantics by advancing the iterator sequentially across nodes, avoiding re-iteration while maintaining correctness for iterator inputs.
**Why This Works:**
- Set membership testing (`n["id"] not in sources`) is O(1) average case, versus O(M) for the `all()` scan
- Building the set requires one pass through edges (O(M)), then checking all nodes (O(N))
- Total: O(N+M) vs O(N×M)
**Impact on Test Cases:**
The speedup scales dramatically with graph size:
- Small graphs (2-3 nodes): 45-109% faster
- Medium chains (100 nodes): **3026% faster**
- Large trees (511 nodes): **13121% faster**
- Dense graphs (20 fully-connected nodes): **1403% faster**
- Complex patterns (100-node diamonds): **3495% faster**
The optimization is particularly effective for larger graphs or graphs with many edges, where the quadratic behavior of the original becomes prohibitive. Even small graphs benefit from the reduced overhead of set lookups versus repeated linear scans.
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.
📄 4,605% (46.05x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
2.98 milliseconds→63.4 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 46x speedup (4605% improvement) by eliminating the quadratic O(N×M) complexity of the original implementation and replacing it with a linear O(N+M) approach.
Key Optimization:
The original code uses nested iteration via
all(e["source"] != n["id"] for e in edges), which re-scans the entireedgescollection for every node. This creates O(N×M) time complexity where N is the number of nodes and M is the number of edges.The optimized version introduces a smart branching strategy:
For re-iterable collections (lists, tuples - the common case): It builds a set of source IDs in one pass (
sources = {e["source"] for e in edges}), then checks membership with O(1) lookups. This reduces complexity to O(N+M) with minimal O(M) memory overhead.For single-pass iterators: It preserves the original consumption semantics by advancing the iterator sequentially across nodes, avoiding re-iteration while maintaining correctness for iterator inputs.
Why This Works:
n["id"] not in sources) is O(1) average case, versus O(M) for theall()scanImpact on Test Cases:
The speedup scales dramatically with graph size:
The optimization is particularly effective for larger graphs or graphs with many edges, where the quadratic behavior of the original becomes prohibitive. Even small graphs benefit from the reduced overhead of set lookups versus repeated linear scans.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mlf9sxm8and push.