⚡️ Speed up function find_last_node by 34,233%
#215
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.
📄 34,233% (342.33x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
178 milliseconds→520 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 342x speedup by replacing a nested-loop O(N×M) algorithm with a linear O(N+M) approach using a set for membership testing.
Key Optimization:
The original code uses
all(e["source"] != n["id"] for e in edges)for each node, checking every edge repeatedly. For N nodes and M edges, this results in N×M comparisons—catastrophic for large graphs.The optimized version:
edge_source_ids = {e["source"] for e in edges}(O(M))n["id"] not in edge_source_idsWhy This Works:
Python sets provide O(1) average-case lookup via hash tables, versus O(M) for iterating through all edges. For each node, the cost drops from M comparisons to a single hash lookup.
Impact by Test Case:
Workload Suitability:
Without
function_references, we can't confirm hot-path usage, but the optimization is universally beneficial: it maintains correctness while drastically reducing algorithmic complexity. Any workload with moderate-to-large graphs (>100 nodes/edges) will see substantial gains.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mjiyqvy6and push.