⚡️ Speed up function find_last_node by 9,164%#285
Open
codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
Open
⚡️ Speed up function find_last_node by 9,164%#285codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
find_last_node by 9,164%#285codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
Conversation
The optimized code achieves a **92x runtime improvement** (47.1ms → 509μs) by fundamentally changing the algorithm's time 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-compute source set instead of repeated lookups**: The original code uses a nested loop structure - for each node, it checks ALL edges to see if that node appears as a source (`all(e["source"] != n["id"] for e in edges)`). This creates quadratic behavior that becomes expensive as the graph grows. The optimized version: 1. **Builds a set of all source IDs once** (`sources = set(e["source"] for e in edges)`) - O(M) operation 2. **Performs O(1) set membership checks** for each node (`n["id"] not in sources`) instead of O(M) linear scans 3. **Falls back gracefully** to the original approach if edges contain unhashable types (like dicts/lists) or missing "source" keys ## Why This Works Sets in Python use hash tables, making membership checks effectively constant time. By extracting all source IDs upfront, we avoid redundantly scanning the edges list for every single node. The try-except ensures correctness when dealing with edge cases like missing keys or unhashable node IDs. ## Performance Characteristics The optimization shines brightest on larger graphs: - **1000-node chain**: 19.6ms → 125μs (156x faster) - **500-node chain**: 4.82ms → 32.8μs (146x faster) - **Complete graph (50 nodes, 1225 edges)**: 1.60ms → 45.0μs (35x faster) - **Binary tree (127 nodes)**: 187μs → 8.25μs (23x faster) Small graphs see modest improvements (2-3μs → 1-2μs) since the overhead of set construction becomes proportionally larger, but the optimization never regresses on valid inputs. Edge cases like empty nodes or missing keys handle correctly via the fallback path with minimal overhead (2-3μs).
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.
📄 9,164% (91.64x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
47.1 milliseconds→509 microseconds(best of210runs)📝 Explanation and details
The optimized code achieves a 92x runtime improvement (47.1ms → 509μs) by fundamentally changing the algorithm's time 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-compute source set instead of repeated lookups: The original code uses a nested loop structure - for each node, it checks ALL edges to see if that node appears as a source (
all(e["source"] != n["id"] for e in edges)). This creates quadratic behavior that becomes expensive as the graph grows.The optimized version:
sources = set(e["source"] for e in edges)) - O(M) operationn["id"] not in sources) instead of O(M) linear scansWhy This Works
Sets in Python use hash tables, making membership checks effectively constant time. By extracting all source IDs upfront, we avoid redundantly scanning the edges list for every single node. The try-except ensures correctness when dealing with edge cases like missing keys or unhashable node IDs.
Performance Characteristics
The optimization shines brightest on larger graphs:
Small graphs see modest improvements (2-3μs → 1-2μs) since the overhead of set construction becomes proportionally larger, but the optimization never regresses on valid inputs. Edge cases like empty nodes or missing keys handle correctly via the fallback path with minimal overhead (2-3μs).
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mluqtdmvand push.