⚡️ Speed up method Graph.topologicalSort by 28%
#903
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.
📄 28% (0.28x) speedup for
Graph.topologicalSortincode_to_optimize/topological_sort.py⏱️ Runtime :
44.8 milliseconds→34.9 milliseconds(best of32runs)📝 Explanation and details
The optimization achieves a 28% speedup by replacing the inefficient
stack.insert(0, v)operation withstack.append(v)followed by a singlestack.reverse()at the end.Key optimization: The original code used
stack.insert(0, v)intopologicalSortUtil, which is an O(N) operation because it requires shifting all existing elements in the list. This happened for every node processed during the DFS traversal. The optimized version usesstack.append(v)(O(1)) and reverses the entire stack once at the end (O(N)).Why this is faster: For a graph with N nodes, the original approach performs N insertions at index 0, resulting in O(N²) time complexity for stack operations alone. The optimized approach performs N constant-time appends plus one O(N) reverse, reducing the stack operations to O(N) total.
Performance impact analysis: The line profiler shows the critical improvement - the
stack.insert(0, v)line took 3.885e+06 nanoseconds (347.3 ns per hit) in the original, whilestack.append(v)takes only 2.802e+06 nanoseconds (250.5 ns per hit) in the optimized version. The singlestack.reverse()operation is negligible at 17,000 nanoseconds total.Test case benefits: The optimization shows increasing benefits with graph size:
This demonstrates that the optimization scales well with problem size, making it particularly valuable for larger topological sorting tasks.
✅ 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_bl3wa8kb/tmpsbakrcsy/test_concolic_coverage.py::test_Graph_topologicalSortTo edit these changes
git checkout codeflash/optimize-Graph.topologicalSort-mhwrsx6gand push.