⚡️ Speed up function find_last_node by 8,871%
#265
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.
📄 8,871% (88.71x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
11.3 milliseconds→126 microseconds(best of809runs)📝 Explanation and details
The optimized code achieves an 88x speedup by eliminating redundant work through a simple algorithmic improvement:
Original approach (O(N×M) complexity):
all(e["source"] != n["id"] for e in edges)runs for every node candidateOptimized approach (O(N+M) complexity):
{e["source"] for e in edges}n["id"] not in sources) for each nodeWhy this matters:
The test results show dramatic improvements for larger inputs:
test_large_scale_many_nodes_and_edges(500 nodes): 17,540% faster (4.56ms → 25.8μs)test_large_linear_chain(500 nodes): 17,456% faster (4.53ms → 25.8μs)test_large_multiple_endpoint_graph(100 nodes, 100 edges): 3,151% faster (203μs → 6.25μs)Smaller graphs (2-10 nodes) still see 100-137% speedups due to eliminating the nested loop overhead.
Behavioral preservation:
KeyErrorfor malformed edges missing "source" key (same as original)The optimization is particularly valuable for graph analysis workflows where this function might be called repeatedly on moderate-to-large graphs, as the performance gain scales quadratically with input size.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-ml2evaghand push.