Sub topic 1
What Is a Longest Increasing Subsequence?
Prerequisites
This chapter assumes you can read basic Python, index into arrays, and reason about Big-O cost. It also assumes you know basic dynamic programming, meaning subproblems and recurrences.
Subsequences and the LIS Problem
A subsequence keeps some elements of a sequence in their original order. Gaps between the kept elements are allowed. From [10, 9, 2, 5, 3, 7, 101, 18], the list [2, 5, 7, 101] is a subsequence. The list [5, 2] is not, because it reverses the order of the two elements.
The longest increasing subsequence (LIS) is the longest subsequence whose values rise from each element to the next. In a strictly increasing subsequence each value is greater than the one before it. In a non-decreasing subsequence equal neighbours are allowed. This chapter uses strictly increasing. The example array has an LIS of length 4.
Why Brute Force Fails: 2^n Subsequences
Each element is either kept or dropped, so an array of n elements has 2^n subsequences. Checking every one costs O(n · 2^n) time. For n = 40 that is already about a trillion subsequences, so brute force only works for very small inputs.
The O(n^2) Dynamic Program
Let dp[i] be the length of the longest increasing subsequence that ends exactly at index i. Such a subsequence is either a[i] alone or an increasing subsequence ending at some earlier j with a[j] < a[i], followed by a[i]:
dp[i] = 1 + max(dp[j] for j < i if a[j] < a[i]), or 1 if no such j exists.
The answer is max(dp), because the LIS could end at any index.
def lis_length_quadratic(a):
if not a:
return 0
dp = [1] * len(a) # dp[i] = length of LIS ending at index i
for i in range(len(a)):
for j in range(i):
if a[j] < a[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp)
print(lis_length_quadratic([10, 9, 2, 5, 3, 7, 101, 18])) # 4Recovering the Subsequence with Parent Pointers
To get the subsequence itself, record in parent[i] the index j that last improved dp[i]. Then start at the index with the largest dp value and follow the parent pointers backwards.
def lis_sequence_quadratic(a):
if not a:
return []
n = len(a)
dp = [1] * n
parent = [-1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
parent[i] = j
i = max(range(n), key=lambda k: dp[k])
seq = []
while i != -1:
seq.append(a[i])
i = parent[i]
return seq[::-1]
print(lis_sequence_quadratic([10, 9, 2, 5, 3, 7, 101, 18])) # [2, 5, 7, 101]Both functions run in O(n^2) time and O(n) space.
Exercise
Compute the dp array for [0, 1, 0, 3, 2, 3] and give the LIS length.
Show answer
dp = [1, 2, 1, 3, 3, 4], so the LIS length is 4, for example [0, 1, 2, 3].
Exercise
What change to the comparison makes the DP compute the longest non-decreasing subsequence?
Show answer
Replace a[j] < a[i] with a[j] <= a[i], so equal values can extend a subsequence.