⚡️ Speed up function find_last_node by 12,973%
#236
+2
−1
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.
📄 12,973% (129.73x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
44.6 milliseconds→341 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 130x speedup by eliminating a nested loop antipattern that caused quadratic time complexity.
What changed:
The original code used a nested comprehension:
all(e["source"] != n["id"] for e in edges)inside(n for n in nodes ...). This meant for each node, it iterated through ALL edges to check if that node was a source, resulting in O(n × m) complexity where n = number of nodes and m = number of edges.The optimization precomputes a set of all source IDs once:
source_ids = {e["source"] for e in edges}. Then for each node, it performs a single O(1) set membership test:n["id"] not in source_ids. This reduces complexity to O(n + m).Why it's faster:
Test case performance:
The optimization is particularly valuable when this function is called in hot paths processing workflow graphs, DAGs, or dependency trees 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-mjs9q8xqand push.