⚡️ Speed up function find_last_node by 23,403%
#219
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.
📄 23,403% (234.03x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
81.2 milliseconds→345 microseconds(best of250runs)📝 Explanation and details
The optimized code is significantly faster because it eliminates a quadratic time complexity nested loop by preprocessing the edges into a set data structure.
Key optimization:
all(e["source"] != n["id"] for e in edges), which iterates through ALL edges to check if the node is a source. This results in O(n × m) complexity where n = number of nodes and m = number of edges.source_ids = {e["source"] for e in edges}), then checks membership withn["id"] not in source_ids. Set membership checking is O(1), reducing overall complexity to O(n + m).Why this matters:
The speedup is most dramatic on large graphs with many edges:
test_large_linear_chain: 18ms → 54μs (333x faster) - 1000 nodes in a chaintest_large_graph_no_terminal_nodes: 18ms → 54μs (332x faster) - 1000 nodes in a cycletest_large_graph_some_disconnected: 4.5ms → 27.5μs (162x faster) - 500 node chainEven small graphs show 50-86% speedups, with minimal overhead. The only case showing slight slowdown is
test_empty_nodes_and_edges(9-14% slower), where the set construction overhead isn't amortized, but this is negligible in absolute terms (< 1 microsecond difference).Performance characteristics:
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mjj0n8x5and push.