⚡️ Speed up function find_leaf_nodes
by 18,209%
#28
+4
−10
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.
📄 18,209% (182.09x) speedup for
find_leaf_nodes
insrc/dsa/nodes.py
⏱️ Runtime :
147 milliseconds
→804 microseconds
(best of133
runs)📝 Explanation and details
Let's analyze and aggressively optimize your code based on the provided profiler.
Bottleneck
The main time cost comes from this loop.
This is O(N*M) where N is the number of nodes and M is the number of edges—very expensive.
The profiler confirms that nearly all of your program's time is spent inside the nested edge loop.
Faster Approach
Rather than scan all edges for each node, collect all node ids with outgoing edges first (i.e., all edge["source"]) using a set for O(1) lookups.
set
of node ids with outgoing edges:source_ids = {edge["source"] for edge in edges}
"id"
is not insource_ids
is a leaf.This reduces complexity from O(N*M) to O(N+M).
Code Rewrite
Notes
Summary of Optimization
This rewrite should drastically reduce the runtime (by orders of magnitude for large inputs) compared to the original.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-find_leaf_nodes-mc8q8rz4
and push.