Longest Increasing Subsequence – Solution & Complexity
Solution Walkthrough
Step 1: Understanding the Problem
- A subsequence keeps the original order but may skip elements.
- We want the longest run of values that strictly increase from left to right.
- We only need the length, not the actual subsequence.
Step 2: Simple O(n^2) DP
- Let
dp[i]be the length of the longest increasing subsequence that ends at indexi. - For each
i, look back at everyj < i; ifnums[j] < nums[i], we can extend that subsequence. - The answer is the maximum value in
dp.
- Let
Step 3: Optimizing with Patience Sorting
- Keep a list
subwheresub[k]is the smallest possible tail of an increasing subsequence of lengthk + 1. - For each number, binary search for the first tail
>=it. - Replacing that tail keeps
subsorted and as small as possible, leaving room to grow.
- Keep a list
Step 4: Why It Works
subis never the real subsequence, but its length always equals the LIS length so far.- Using
bisect_leftenforces strictly increasing values (equal numbers overwrite rather than extend). - That is why
[7,7,7,...]correctly returns1.
Step 5: Complexity
- Time:
O(n log n)thanks to the binary search per element. - Space:
O(n)for thesubarray in the worst case.
- Time: