⚡️ Speed up function longest_increasing_subsequence_length by 40,778%#1072
Closed
codeflash-ai[bot] wants to merge 1 commit into
Closed
⚡️ Speed up function longest_increasing_subsequence_length by 40,778%#1072codeflash-ai[bot] wants to merge 1 commit into
longest_increasing_subsequence_length by 40,778%#1072codeflash-ai[bot] wants to merge 1 commit into
Conversation
The optimized code achieves a **408x speedup** by replacing the O(n²) dynamic programming algorithm with an O(n log n) patience sorting approach using binary search. **Key algorithmic change:** - **Original approach**: Nested loops comparing every element with all previous elements (O(n²) complexity). The line profiler shows the inner loop executed 1.6M times, consuming 23.2% of total runtime, with comparison operations taking another 33.4%. - **Optimized approach**: Maintains a sorted `tails` array where `tails[k]` stores the smallest tail value of any increasing subsequence of length `k+1`. For each element, uses `bisect.bisect_left()` to find its insertion position in O(log n) time. **Why this is faster:** 1. **Eliminates nested iteration**: Instead of comparing each element with all previous elements (1.6M comparisons in the profiler), we perform just one binary search per element (~5,800 searches for ~5,800 elements). 2. **Leverages optimized C implementation**: Python's `bisect` module is implemented in C and highly optimized for sorted list operations. 3. **Reduces memory operations**: No repeated array indexing in tight loops. The `tails` list grows incrementally and stays small (max length = LIS length, not input length). **Performance characteristics from test results:** - **Small arrays** (< 10 elements): Modest 20-150% speedup due to overhead being comparable to the O(n²) work. - **Medium arrays** (~30-100 elements): 2,000-23,000% speedup as the quadratic penalty becomes significant. - **Large arrays** (400-500 elements): **31,000-96,000% speedup** - the profiler shows original runtime of 3.66s vs optimized 16.7ms for the same workload. - **Worst-case patterns**: Descending sequences show 31,707% speedup (was O(n²) comparisons with no updates, now O(n log n) searches). **Impact considerations:** The optimization maintains identical correctness (handles integers, floats, negatives, duplicates, edge cases) while dramatically improving performance on any input size > ~10 elements. Given the massive speedup on realistic data sizes, this change would benefit any workload calling this function repeatedly or on non-trivial arrays.
Contributor
Author
|
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.
📄 40,778% (407.78x) speedup for
longest_increasing_subsequence_lengthincode_to_optimize/sample_code.py⏱️ Runtime :
859 milliseconds→2.10 milliseconds(best of79runs)📝 Explanation and details
The optimized code achieves a 408x speedup by replacing the O(n²) dynamic programming algorithm with an O(n log n) patience sorting approach using binary search.
Key algorithmic change:
tailsarray wheretails[k]stores the smallest tail value of any increasing subsequence of lengthk+1. For each element, usesbisect.bisect_left()to find its insertion position in O(log n) time.Why this is faster:
bisectmodule is implemented in C and highly optimized for sorted list operations.tailslist grows incrementally and stays small (max length = LIS length, not input length).Performance characteristics from test results:
Impact considerations:
The optimization maintains identical correctness (handles integers, floats, negatives, duplicates, edge cases) while dramatically improving performance on any input size > ~10 elements. Given the massive speedup on realistic data sizes, this change would benefit any workload calling this function repeatedly or on non-trivial arrays.
✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
test_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_all_same_elementstest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_alternating_sequencetest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_classic_exampletest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_empty_arraytest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_float_valuestest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_longer_sequencetest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_negative_numberstest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_single_elementtest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_strictly_decreasingtest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_strictly_increasingtest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_two_elements_decreasingtest_numba_jit_code.py::TestLongestIncreasingSubsequenceLength.test_two_elements_increasing🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-longest_increasing_subsequence_length-mkgfjtjcand push.