⚡️ Speed up function find_node_with_highest_degree by 5,727%#284
Open
codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
Open
⚡️ Speed up function find_node_with_highest_degree by 5,727%#284codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
find_node_with_highest_degree by 5,727%#284codeflash-ai[bot] wants to merge 1 commit intopython-onlyfrom
Conversation
The optimized code achieves a **5726% speedup** (from 160ms to 2.74ms) by eliminating a critical algorithmic inefficiency in how incoming connections are counted.
**Key Optimization:**
The original code uses a nested loop structure that scans *all* connections for *every* node to count incoming edges:
```python
for node in nodes: # O(N) nodes
for src, targets in connections.items(): # O(E) edges - repeated N times!
if node in targets: # O(T) target list check
```
This creates O(N × E × T) complexity. The line profiler shows these two nested loops consuming 99.1% of total runtime (48.3% + 50.8%).
The optimized code **precomputes** incoming connection counts in a single upfront pass:
```python
incoming_counts: dict[str, int] = {}
for src, targets in connections.items(): # O(E) - done once
for target in set(targets): # O(T) per source
incoming_counts[target] = incoming_counts.get(target, 0) + 1
```
Then during the node iteration, incoming degree lookup becomes O(1):
```python
degree += incoming_counts.get(node, 0) # Simple dict lookup
```
**Why This Works:**
- **Algorithmic improvement**: Changes from O(N × E × T) to O(E × T + N), which is dramatically faster when graphs have many nodes
- **Single-pass aggregation**: Incoming connections are counted once and cached, rather than recomputed for each node
- **Deduplication**: Using `set(targets)` ensures duplicate targets in a source's list are counted only once per source (matching the original behavior where `if node in targets` would only increment once per source)
**Impact on Workloads:**
The test results show the optimization excels with larger graphs:
- Small graphs (2-3 nodes): 8-27% slower due to setup overhead
- Medium graphs (50-500 nodes): 258-4524% faster
- Large graphs (1000 nodes): 10826% faster
The performance benefit scales with graph size because the precomputation cost (O(E × T)) is amortized across all nodes, while the original O(N × E × T) cost grows multiplicatively with the number of nodes being analyzed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
📄 5,727% (57.27x) speedup for
find_node_with_highest_degreeinsrc/algorithms/graph.py⏱️ Runtime :
160 milliseconds→2.74 milliseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 5726% speedup (from 160ms to 2.74ms) by eliminating a critical algorithmic inefficiency in how incoming connections are counted.
Key Optimization:
The original code uses a nested loop structure that scans all connections for every node to count incoming edges:
This creates O(N × E × T) complexity. The line profiler shows these two nested loops consuming 99.1% of total runtime (48.3% + 50.8%).
The optimized code precomputes incoming connection counts in a single upfront pass:
Then during the node iteration, incoming degree lookup becomes O(1):
Why This Works:
set(targets)ensures duplicate targets in a source's list are counted only once per source (matching the original behavior whereif node in targetswould only increment once per source)Impact on Workloads:
The test results show the optimization excels with larger graphs:
The performance benefit scales with graph size because the precomputation cost (O(E × T)) is amortized across all nodes, while the original O(N × E × T) cost grows multiplicatively with the number of nodes being analyzed.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_node_with_highest_degree-mlumboqband push.