⚡️ Speed up function find_last_node by 4,704%#267
Closed
codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Closed
⚡️ Speed up function find_last_node by 4,704%#267codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
find_last_node by 4,704%#267codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Conversation
The optimized code achieves a **4703% speedup** (from 11.5ms to 238μs) by replacing an O(N×M) nested loop with O(N+M) operations using a set-based lookup strategy.
**Key Optimization:**
The original code uses a nested generator expression: for each node, it iterates through ALL edges to check if that node is a source. This creates O(N×M) comparisons where N is the number of nodes and M is the number of edges.
The optimized code:
1. Pre-builds a set of all edge sources in a single pass: `sources = {e["source"] for e in edges}` - O(M) time
2. Checks each node against this set using O(1) hash lookups: `if n["id"] not in sources` - O(N) time
3. Total complexity: O(N+M) instead of O(N×M)
**Why This Works:**
Python sets use hash tables, making membership checks nearly instantaneous regardless of set size. Instead of comparing each node against every edge repeatedly, we build the set once and perform fast lookups.
**Performance Impact by Test Case:**
- **Small graphs** (2-4 nodes): 40-111% faster - modest gains due to setup overhead
- **Medium graphs** (100-200 nodes): 1,219-2,966% faster - optimization starts paying off significantly
- **Large linear chains** (500 nodes): 7,925-16,291% faster - dramatic improvement as the quadratic cost of the original becomes prohibitive
- **Dense graphs** (500 nodes, 1000 edges): 2,517-5,540% faster - set lookup shines with many edges
- **Empty edges**: Still fast (47-69% faster) due to early return path
**Edge Case Preservation:**
The code carefully handles the original behavior where nodes without an 'id' key don't raise KeyError when edges is empty (the `all()` short-circuits without evaluating `n["id"]`). The optimized version checks `if sources:` before accessing `n["id"]`, preserving this quirk.
**Conclusion:**
This optimization transforms a quadratic algorithm into a linear one, making it dramatically faster for realistic graph sizes (100+ nodes) while maintaining identical behavior for all edge 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.
📄 4,704% (47.04x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
11.5 milliseconds→238 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 4703% speedup (from 11.5ms to 238μs) by replacing an O(N×M) nested loop with O(N+M) operations using a set-based lookup strategy.
Key Optimization:
The original code uses a nested generator expression: for each node, it iterates through ALL edges to check if that node is a source. This creates O(N×M) comparisons where N is the number of nodes and M is the number of edges.
The optimized code:
sources = {e["source"] for e in edges}- O(M) timeif n["id"] not in sources- O(N) timeWhy This Works:
Python sets use hash tables, making membership checks nearly instantaneous regardless of set size. Instead of comparing each node against every edge repeatedly, we build the set once and perform fast lookups.
Performance Impact by Test Case:
Edge Case Preservation:
The code carefully handles the original behavior where nodes without an 'id' key don't raise KeyError when edges is empty (the
all()short-circuits without evaluatingn["id"]). The optimized version checksif sources:before accessingn["id"], preserving this quirk.Conclusion:
This optimization transforms a quadratic algorithm into a linear one, making it dramatically faster for realistic graph sizes (100+ nodes) while maintaining identical behavior for all edge cases.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
📊 Performance Profile
View detailed line-by-line performance analysis
To edit these changes
git checkout codeflash/optimize-find_last_node-ml2jdrqxand push.