Longest Increasing Subsequence Problem
Description
LeetCode Problem 300.
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7]
Output: 1
Constraints:
- 1 <= nums.length <= 2500
- -10^4 <= nums[i] <= 10^4
Solution
Approach: Smallest Tails with Binary Search
The classic DP compares every pair of positions and takes O(n2) time. We can do better by keeping, for every length, only the most useful subsequence of that length.
Let tails[k] be the smallest last element of any strictly increasing subsequence of length k + 1 found so far. A smaller last element is always better, because more future numbers can extend it. tails is strictly increasing: a subsequence of length k + 2 contains one of length k + 1 that ends on a smaller element.
For each number x:
- Binary search for the first index
iwithtails[i] >= x. - If there is none,
xis larger than every tail and extends the longest subsequence: append it. - Otherwise set
tails[i] = x. The subsequence of lengthithat ends attails[i - 1] < x, followed byx, is a subsequence of lengthi + 1with a smaller end than before.
The answer is the length of tails. Note that tails itself is not always a real subsequence of nums; only its length is meaningful.
The search must find the first tail >= x, not > x. With [7, 7], the second 7 has to replace the first one; looking for > x would append it and count [7, 7] as increasing.
For [10, 9, 2, 5, 3, 7, 101, 18], tails goes [10], [9], [2], [2, 5], [2, 3], [2, 3, 7], [2, 3, 7, 101], [2, 3, 7, 18], so the answer is 4.
Complexity: O(n log n) time and O(n) space, where n is the length of nums.
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
# tails[k] = the smallest last element of an increasing subsequence of length k + 1.
# tails is always strictly increasing, so it can be binary searched.
tails = []
for x in nums:
# Find the first tail >= x (the subsequence must be strictly increasing).
low, high = 0, len(tails)
while low < high:
mid = (low + high) // 2
if tails[mid] < x:
low = mid + 1
else:
high = mid
if low == len(tails):
tails.append(x) # x extends the longest subsequence so far
else:
tails[low] = x # x is a smaller end for subsequences of length low + 1
return len(tails)
Now write it from memory
Close the write-up and solve it yourself against the tests.