⚡️ Speed up function find_node_with_highest_degree
by 2,940%
#68
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.
📄 2,940% (29.40x) speedup for
find_node_with_highest_degree
insrc/dsa/nodes.py
⏱️ Runtime :
34.0 milliseconds
→1.12 milliseconds
(best of1028
runs)📝 Explanation and details
The optimized code achieves a 2939% speedup by eliminating the nested loop that was causing O(n²) behavior in the original implementation.
Key Optimization: Precomputing In-Degrees
The original code counted incoming connections by iterating through all connection entries for every node:
This created O(N × C × T) complexity where N=nodes, C=connections, T=targets per connection.
The optimized version precomputes all in-degrees in a single pass:
Then simply looks up each node's in-degree in O(1):
in_deg = in_degree.get(node, 0)
Performance Impact Analysis:
From the line profiler results, the bottleneck was eliminated:
Complexity Improvement:
Test Case Performance Patterns:
The optimization shows dramatic improvements on larger, denser graphs:
For small graphs (≤3 nodes), the optimization shows modest 5-15% gains or even slight regressions due to preprocessing overhead, but this is negligible compared to the massive gains on realistic graph sizes.
The optimization is particularly effective for graphs with many connections or high in-degrees, where the original nested loop would perform many redundant scans.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-find_node_with_highest_degree-mdpdzwh0
and push.