⚡️ Speed up function find_last_node by 16,984%#280
Open
codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Open
⚡️ Speed up function find_last_node by 16,984%#280codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
find_last_node by 16,984%#280codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Conversation
The optimized code achieves a **170x speedup** (from 148ms to 869μs) by replacing an O(n×m) algorithm with an O(n+m) approach through intelligent set-based lookup.
## Key Optimization
**Set-based source tracking**: Instead of checking each node against all edges (nested iteration), the code pre-computes a set of all source node IDs once:
```python
source_ids = {e["source"] for e in edges}
```
This transforms the expensive `all(e["source"] != n["id"] for e in edges)` check (O(m) per node) into a simple `n["id"] not in source_ids` membership test (O(1) per node).
## Why This Works
The line profiler shows the dramatic impact:
- **Original**: Single line taking 1.49 seconds (100% of runtime) due to nested iteration
- **Optimized**: Set creation (66.3%) + fast lookups (30.4%) = only 1.2ms total
For graphs with many edges, the optimization becomes more pronounced. The test results demonstrate this scaling:
- 1000-node linear chain: **192x faster** (19.2ms → 104μs)
- 1000-node cycle: **385x faster** (18.2ms → 47.3μs)
- Complex DAG with 2500+ edges: **254x faster** (54.2ms → 212μs)
## Edge Case Handling
The code includes a try-except fallback to preserve original behavior when:
1. Node IDs are **unhashable types** (like lists) - these can't be added to sets
2. Nodes are **malformed** (missing "id" key or not dicts)
This ensures correctness while delivering massive speedups for the common case of hashable IDs (strings, integers, tuples).
## Test Impact
The optimization excels for graphs with:
- **Many edges**: Dense graphs see 46-254x speedups as set lookup avoids repeated edge scanning
- **Large node counts**: The O(n+m) complexity scales far better than O(n×m)
- **Hashable IDs**: All standard types (strings, numbers) benefit fully
Small graphs (≤10 nodes/edges) still improve 20-110%, with negligible overhead from the try-except block in the unhashable fallback path.
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.
📄 16,984% (169.84x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
148 milliseconds→869 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 170x speedup (from 148ms to 869μs) by replacing an O(n×m) algorithm with an O(n+m) approach through intelligent set-based lookup.
Key Optimization
Set-based source tracking: Instead of checking each node against all edges (nested iteration), the code pre-computes a set of all source node IDs once:
This transforms the expensive
all(e["source"] != n["id"] for e in edges)check (O(m) per node) into a simplen["id"] not in source_idsmembership test (O(1) per node).Why This Works
The line profiler shows the dramatic impact:
For graphs with many edges, the optimization becomes more pronounced. The test results demonstrate this scaling:
Edge Case Handling
The code includes a try-except fallback to preserve original behavior when:
This ensures correctness while delivering massive speedups for the common case of hashable IDs (strings, integers, tuples).
Test Impact
The optimization excels for graphs with:
Small graphs (≤10 nodes/edges) still improve 20-110%, with negligible overhead from the try-except block in the unhashable fallback path.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mlfsladtand push.