⚡️ Speed up method Graph.topologicalSort by 140% #890
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.
📄 140% (1.40x) speedup for
Graph.topologicalSortincode_to_optimize/topological_sort.py⏱️ Runtime :
2.67 milliseconds→1.11 milliseconds(best of13runs)📝 Explanation and details
The optimized code achieves a 140% speedup by replacing an inefficient list operation with a more performant approach. The key optimization is changing
stack.insert(0, v)tostack.append(v)followed by a singlestack.reverse()call.What changed:
topologicalSortUtil:stack.insert(0, v)→stack.append(v)topologicalSort: Addedstack.reverse()before returningvisited[i] == False→not visited[i](slightly more Pythonic)Why this is faster:
The original code performs
stack.insert(0, v)for every node visited, which is an O(N) operation since Python lists must shift all existing elements when inserting at the head. For a graph with N nodes, this results in O(N²) total time complexity just for list operations.The optimized version uses
stack.append(v)(O(1) operation) for each node, then performs a singlestack.reverse()(O(N)) at the end. This reduces the list operation complexity from O(N²) to O(N).Performance impact:
The line profiler shows the stack operation time dropped from 3.06ms (21% of total time) to 1.78ms (12.6% of total time) in
topologicalSortUtil. The optimization is particularly effective for larger graphs - test cases show 157-197% speedup for graphs with 1000 nodes, while smaller graphs (≤5 nodes) show minimal or mixed results since the O(N²) vs O(N) difference isn't significant at small scales.This optimization maintains identical functionality and correctness while dramatically improving performance for larger topological sorting workloads.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_7dnvqc5e/tmptwugmlm2/test_concolic_coverage.py::test_Graph_topologicalSortTo edit these changes
git checkout codeflash/optimize-Graph.topologicalSort-mhq0bhxyand push.