⚡️ Speed up function find_last_node by 21,472%
#234
+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.
📄 21,472% (214.72x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
77.8 milliseconds→360 microseconds(best of250runs)📝 Explanation and details
The optimization transforms an O(n × m) nested loop into an O(n + m) linear scan by eliminating redundant edge traversals.
What changed:
all(e["source"] != n["id"] for e in edges)for every node (which scans all edges repeatedly), the code now builds a setsource_idscontaining all source IDs upfrontWhy it's faster:
In the original code, for each node, Python iterates through every edge to verify none has that node as a source. With N nodes and M edges, this results in N × M comparisons.
The optimized version:
source_idsset in one pass: O(M) time, O(M) spaceThis is a classic space-time tradeoff: we use O(M) additional memory for massive time savings.
Performance impact:
The optimization particularly shines when there are many edges to check against each node, transforming what would be prohibitively slow for production graphs into microsecond-level performance.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mjnhr8myand push.