⚡️ Speed up function find_last_node by 13,688%#237
Closed
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Closed
⚡️ Speed up function find_last_node by 13,688%#237codeflash-ai[bot] wants to merge 1 commit intomainfrom
find_last_node by 13,688%#237codeflash-ai[bot] wants to merge 1 commit intomainfrom
Conversation
The optimized code achieves a **137x speedup** by replacing an O(N×M) nested loop with an O(M+N) set-based lookup approach.
**Key optimization:**
The original code uses a nested iteration pattern:
```python
all(e["source"] != n["id"] for e in edges)
```
For each node, this checks ALL edges to verify none have that node as a source. With N nodes and M edges, this creates N×M comparisons in the worst case.
The optimized code pre-computes a set of source node IDs:
```python
sources = {e["source"] for e in edges}
return next((n for n in nodes if n["id"] not in sources), None)
```
This builds the source set once (O(M)) and then performs O(1) set membership checks for each node (O(N)), resulting in O(M+N) total complexity.
**Why this matters:**
The speedup is dramatic on larger graphs. Test results show:
- **Large linear chain (1000 nodes):** 18.4ms → 58.4μs (**314x faster**)
- **Large cycle (1000 nodes):** 18.3ms → 57.6μs (**316x faster**)
- **Dense graph (100 nodes, 2500 edges):** 2.23ms → 52.8μs (**42x faster**)
Even small graphs benefit significantly (60-100% speedups) because set construction and lookup are highly optimized in Python, while the nested `all()` with generator expressions has per-iteration overhead.
**Edge case handling:**
The `if not edges:` check preserves the original behavior where an empty edge list allows returning the first node without accessing `n["id"]`, avoiding `KeyError` when nodes lack an 'id' field. This maintains backward compatibility while enabling the optimization for all normal cases.
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.
📄 13,688% (136.88x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
57.8 milliseconds→419 microseconds(best of225runs)📝 Explanation and details
The optimized code achieves a 137x speedup by replacing an O(N×M) nested loop with an O(M+N) set-based lookup approach.
Key optimization:
The original code uses a nested iteration pattern:
For each node, this checks ALL edges to verify none have that node as a source. With N nodes and M edges, this creates N×M comparisons in the worst case.
The optimized code pre-computes a set of source node IDs:
This builds the source set once (O(M)) and then performs O(1) set membership checks for each node (O(N)), resulting in O(M+N) total complexity.
Why this matters:
The speedup is dramatic on larger graphs. Test results show:
Even small graphs benefit significantly (60-100% speedups) because set construction and lookup are highly optimized in Python, while the nested
all()with generator expressions has per-iteration overhead.Edge case handling:
The
if not edges:check preserves the original behavior where an empty edge list allows returning the first node without accessingn["id"], avoidingKeyErrorwhen nodes lack an 'id' field. This maintains backward compatibility while enabling the optimization for all normal cases.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mjsbm2ytand push.