Longest increasing subsequence
🌍 In real life. Rumana's monthly test marks this year were 5, 2, 8, 6, 3, 6, 9, 7 out of 10. Her teacher asks: what is the longest set of months, in order, where each mark beats the one before? The months don't have to be next to each other: 2, 3, 6, 9 is four months of steady improvement, and no five months are.
The idea in one sentence: let dp[i] be the length of the longest increasing run that ends with nums[i]; the number before nums[i] in that run is some earlier, smaller nums[j], so dp[i] is 1 more than the best such dp[j], and the answer is the largest cell.
Its words:
- increasing subsequence: numbers taken in order, each strictly bigger than the one before, gaps allowed
- ends with: the state fixes the last number, which is what lets the next number check "am I bigger?"
- the answer is a maximum: the best run can end anywhere, so it is
max(dp), not the last cell
Step by step:
- every
dp[i]starts at 1 (the number alone) - for each earlier
jwithnums[j] < nums[i]:dp[i] = max(dp[i], dp[j] + 1) - the answer is
max(dp)
Watch the runs grow: the marks sit above their cells, and the arrows come from every earlier, lower mark:
Why it is right. Take a longest run that ends with nums[i]. If it has more than one number, the one before nums[i] is some nums[j] with j < i and nums[j] < nums[i], and the run up to it is a run ending with nums[j], so it is at most dp[j] long. Trying every such j therefore finds the best.
A faster way. Keep tails, where tails[k] is the smallest number that can end an increasing run of length k + 1. The list stays sorted, so for each number a binary search (bisect_left, Chapter 43) finds the first tail it can replace, or it extends the list. The length of tails is the answer, though tails itself is not always a real run.
What it costs, by counting. The table compares every pair: for 10,000 marks, about 10,000 × 10,000 / 2 = 50,000,000 comparisons. The tails way does one binary search per number: about 10,000 × 14 = 140,000 steps. In Big-O: the table is O(n²) time and O(n) memory; the tails way is O(n log n) time and O(n) memory.
def lis_length(nums):
if not nums:
return 0
dp = [1] * len(nums) # dp[i]: the longest increasing run ending with nums[i]
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]: # nums[i] can follow nums[j]
dp[i] = max(dp[i], dp[j] + 1)
return max(dp) # the best run can end anywhere
from bisect import bisect_left
def lis_fast(nums):
tails = [] # tails[k]: the smallest last number of an increasing run of length k + 1
for x in nums:
k = bisect_left(tails, x) # the first tail that is not smaller than x
if k == len(tails):
tails.append(x) # x makes the longest run so far one longer
else:
tails[k] = x # a run of length k + 1 can now end lower
return len(tails)
marks = [5, 2, 8, 6, 3, 6, 9, 7]
print(lis_length(marks), lis_fast(marks))
print(lis_fast(list(range(1000))))Mistakes and edge cases.
- returning the last cell:
dp[-1]is only the best run ending with the last number; takemax(dp) - stretches or subsequences: next-to-each-other increasing stretches are a different, easier question; 5, 2, 8, 6, 3, 6, 9, 7 has no stretch longer than 3
- strictly increasing: equal numbers don't count, so
[7, 7, 7]has a longest increasing subsequence of 1; withbisect_rightthe fast way would count repeats - an empty list:
max([])raises an error; return 0 first
Quiz
What does dp[i] mean here?
- The longest increasing run that ends with nums[i]
- The longest increasing run among the first i numbers
- How many numbers before nums[i] are smaller
What does this print?
def lis_length(nums): if not nums: return 0 dp = [1] * len(nums) # dp[i]: the longest increasing run ending with nums[i] for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: # nums[i] can follow nums[j] dp[i] = max(dp[i], dp[j] + 1) return max(dp) # the best run can end anywhere print(lis_length([10, 9, 2, 5, 3, 7, 101, 18]))What does this print?
def lis_length(nums): if not nums: return 0 dp = [1] * len(nums) # dp[i]: the longest increasing run ending with nums[i] for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: # nums[i] can follow nums[j] dp[i] = max(dp[i], dp[j] + 1) return max(dp) # the best run can end anywhere print(lis_length([3, 2, 1]))About how many steps does the tails-and-bisect way take for 10,000 numbers?
- About 140,000: one binary search per number
- About 50,000,000
- 10,000
lis_length([5, 6, 1]) gives 1 instead of 2. Which line is wrong?
def lis_length(nums): if not nums: return 0 dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j] + 1) return dp[-1]
Coding tasks
Write
lis_length(nums): the length of the longest strictly increasing subsequence ofnums(numbers in order, gaps allowed).Write
lis_fast(nums): the same length, using a sorted listtailsandbisect_left, so each number costs one binary search.