⚡️ Speed up method Graph.topologicalSort by 62%
#815
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.
📄 62% (0.62x) speedup for
Graph.topologicalSortincode_to_optimize/topological_sort.py⏱️ Runtime :
2.31 milliseconds→1.43 milliseconds(best of17runs)📝 Explanation and details
The optimization achieves a 61% speedup by eliminating an expensive O(n) list operation that was being called repeatedly.
Key optimization:
Replaced
stack.insert(0, v)withstack.append(v)+ finalstack.reverse(): The original code usedinsert(0, v)to prepend elements to the stack, which requires shifting all existing elements and costs O(n) time per insertion. With 7,163 calls to this operation (as shown in the profiler), this became a significant bottleneck consuming 16.6% of the function's time.Changed boolean comparisons: Replaced
visited[i] == Falsewithnot visited[i]for slightly cleaner, more Pythonic code.Why this works:
The topological sort algorithm needs to output vertices in reverse post-order. Instead of building this order directly with expensive prepends, the optimized version builds the reverse order efficiently with O(1) appends, then reverses the entire list once at the end. Since
list.reverse()is O(n) but only called once versus O(n) operations called thousands of times, this dramatically reduces the time complexity from O(n²) to O(n) for the stack operations.Performance characteristics:
The optimization particularly excels with larger graphs (as seen in the large-scale test cases with 1000+ nodes) where the quadratic behavior of repeated insertions becomes most apparent. For smaller graphs, the improvement is still measurable but less dramatic.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Graph.topologicalSort-mgpn9byeand push.