⚡️ Speed up method Graph.topologicalSort by 61%
#939
Closed
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.
📄 61% (0.61x) speedup for
Graph.topologicalSortincode_to_optimize/topological_sort.py⏱️ Runtime :
14.2 milliseconds→8.79 milliseconds(best of11runs)📝 Explanation and details
The optimization transforms the core bottleneck from O(N²) to O(N) complexity by changing how the topological sort stack is built.
Key Change: Replaced
stack.insert(0, v)withstack.append(v)followed by a singlestack.reverse().Why This is Faster:
stack.insert(0, v)has O(N) complexity because it shifts all existing elements one position right for each insertionstack.append(v)has O(1) amortized complexity, making stack operations O(N) totalstack.reverse()at the end is O(N), maintaining the correct topological orderPerformance Impact by Test Case:
Minor Optimization: Changed
visited[i] == Falsetonot visited[i]for slightly more Pythonic and marginally faster boolean checks.The optimization scales particularly well with graph size - larger graphs see exponentially better performance due to eliminating the quadratic list shifting behavior. This makes the implementation suitable for real-world applications with substantial graph sizes.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_topological_sort.py::test_topological_sorttest_topological_sort.py::test_topological_sort_2test_topological_sort.py::test_topological_sort_3🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_7f254fbi/tmpuqq470t0/test_concolic_coverage.py::test_Graph_topologicalSortTo edit these changes
git checkout codeflash/optimize-Graph.topologicalSort-micckrt6and push.