Longest Increasing Subsequence – Solution & Complexity
Watch: Longest Increasing Subsequence with dp[i], the best run ending at i
Taking every bigger number fails: on 3, 10, 2, 3, 4 it takes 3, then 10, and nothing after is bigger than 10, so length 2. Skipping 3 and 10 gives 2, 3, 4, length 3. Instead, let dp[i] be the longest increasing run that ends at i: 1 plus the best dp[j] before it with a smaller number, or 1 if none is smaller. The dp values are 1, 2, 1, 2, 3, and the answer is the biggest: 3. Two loops: O(n²) time, O(n) space.
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: