⚡️ Speed up function find_node_with_highest_degree
by 3,600%
#31
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.
📄 3,600% (36.00x) speedup for
find_node_with_highest_degree
insrc/dsa/nodes.py
⏱️ Runtime :
106 milliseconds
→2.86 milliseconds
(best of244
runs)📝 Explanation and details
Let's analyze and optimize your program.
1. Bottleneck Analysis
The line profiler result shows.
The major bottleneck (~99% time) is this double loop.
This means for every node, we loop over all nodes and their targets looking for "incoming connections".
if node in targets
line takes about 50% of total runtime alone (since this is an O(m) scan inside an O(n) loop).2. Suggestions for Optimization
Precompute Incoming Degree
Rather than checking "for every node, how many lists in connections contain it?", we can precompute the number of incoming connections each node has in a single pass. This avoids O(n^2) behavior and reduces to O(n+m).
Algorithm
len(connections.get(node, []))
connections
.3. Review Installed Distributions
No external libraries are used. The code is pure Python.
4. Optimized Code
Explanation:
incoming_degree
by looping once through all connections; this replaces the O(n^2) code.node
, we only need O(1) lookups for in-degree and out-degree.5. Result
The new code will run orders of magnitude faster—from O(n^2) to O(n + m) for a graph with n nodes and m edges, with minimal extra memory.
Summary
Let me know if you'd like to see additional tweaks or a variant!
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-find_node_with_highest_degree-mc8r96cx
and push.