⚡️ Speed up function find_last_node by 5,211%#270
Closed
codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Closed
⚡️ Speed up function find_last_node by 5,211%#270codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
find_last_node by 5,211%#270codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Conversation
The optimized code achieves a **52x speedup** (5210% faster) by fundamentally changing the algorithmic complexity from O(N*M) to O(N+M), where N is the number of nodes and M is the number of edges.
**Key Optimization: Pre-computing Source Set**
The original code uses a nested loop structure via generator expressions:
```python
next((n for n in nodes if all(e["source"] != n["id"] for e in edges)), None)
```
For each node, it iterates through ALL edges to check if that node appears as a source. This creates O(N*M) comparisons.
The optimized code instead:
1. **Builds a set of all source IDs once**: `sources = {e["source"] for e in edges}` - O(M) operation
2. **Performs O(1) lookups**: `if node_id not in sources` - uses set membership testing
3. **Total complexity**: O(N+M) instead of O(N*M)
**Performance Impact by Test Case:**
- **Small graphs** (2-10 nodes): 60-174% faster - modest gains as overhead of set creation is offset by fewer nodes
- **Medium graphs** (50-100 nodes): 361-1827% faster - the optimization starts to shine
- **Large graphs** (200-500 nodes): 3632-18094% faster - dramatic speedup as the quadratic behavior of the original becomes prohibitive
The test `test_large_scale_chain_of_500_nodes_is_handled_correctly` shows the most dramatic improvement: **5.47ms → 30.1μs (18094% faster)** - because it must check 500 nodes against 499 edges, resulting in nearly 250,000 comparisons in the original vs just ~999 operations in the optimized version.
**Correctness Preservation:**
The optimized code carefully preserves edge cases:
- Falls back to original behavior for non-reiterable iterators (preserves consumption semantics)
- Falls back for unhashable source values (TypeError handling)
- Mimics lazy evaluation for `n["id"]` access when `sources` is empty (returns node without checking id)
- Raises appropriate exceptions (TypeError, KeyError) at the same logical points as the original
This optimization is particularly valuable for graph traversal workflows where finding terminal nodes is a frequent operation on graphs with hundreds of nodes and edges.
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.
📄 5,211% (52.11x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
14.3 milliseconds→269 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 52x speedup (5210% faster) by fundamentally changing the algorithmic complexity from O(N*M) to O(N+M), where N is the number of nodes and M is the number of edges.
Key Optimization: Pre-computing Source Set
The original code uses a nested loop structure via generator expressions:
For each node, it iterates through ALL edges to check if that node appears as a source. This creates O(N*M) comparisons.
The optimized code instead:
sources = {e["source"] for e in edges}- O(M) operationif node_id not in sources- uses set membership testingPerformance Impact by Test Case:
The test
test_large_scale_chain_of_500_nodes_is_handled_correctlyshows the most dramatic improvement: 5.47ms → 30.1μs (18094% faster) - because it must check 500 nodes against 499 edges, resulting in nearly 250,000 comparisons in the original vs just ~999 operations in the optimized version.Correctness Preservation:
The optimized code carefully preserves edge cases:
n["id"]access whensourcesis empty (returns node without checking id)This optimization is particularly valuable for graph traversal workflows where finding terminal nodes is a frequent operation on graphs with hundreds of nodes and edges.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mldfuqcqand push.