Longest Increasing Subsequence

MediumDynamic programmingLeetCode 300 ↗World 5-16
0:00 / 0:00

Find the longest strictly rising run you can pick out of a list, skipping but never reordering. Build the answer for each ending number from the ones before it, then a bonus O(n log n) trick.

▼

The problem

LeetCode 300 (Medium). Given a list of numbers, return the length of the longest strictly increasing subsequence (numbers may be skipped, not reordered).

Example (LeetCode's, the one animated): [10, 9, 2, 5, 3, 7, 101, 18] → 4 (for example 2, 5, 7, 101).

def length_of_lis(nums):
    dp = [1] * len(nums)        # badges
    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 max(dp)
TRY IT ON LEETCODE ▶

The solution

def length_of_lis(nums):
    dp = [1] * len(nums)        # badges
    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 max(dp)

Transcript

Longest Increasing Subsequence. You get a list of numbers. Find the length of the longest subsequence that strictly increases. A subsequence keeps the original order, but you may skip numbers.

Take ten, nine, two, five, three, seven, one hundred and one, eighteen. Two, five, seven, one hundred and one climbs four steps, and nothing climbs five. So the answer is four.

The naive way tries every subsequence. Each number is either in or out, so there are two to the n choices. Eight numbers make two hundred fifty-six. Forty numbers make over a trillion.

Instead, give each pillar a badge: the length of the longest increasing run that ends right there. To fill a badge, look back at every earlier pillar that is lower, take the best badge among them, and add one. Nothing lower behind it? Then the badge is one. The answer is the biggest badge.

In code, every badge starts at one. For each i, check every j before it. If nums j is smaller, badge i becomes the larger of itself and badge j plus one. At the end, return the biggest badge.

Let's climb. Ten, nine and two have nothing lower behind them, so each gets one. Five reaches back to two: two. Three also finds two: two. Seven sees two, five and three. The best badge is two, so seven gets three. One hundred and one builds on seven: four. So does eighteen. Follow the links back from one hundred and one: seven, five, two.

Each pillar looks back at every earlier one. For eight numbers, that's twenty-eight checks. So the time is n squared, and the badges take n space.

Bonus: a faster way keeps the smallest tail for each run length. Each new number binary searches the tails, then replaces the first tail that isn't smaller, or extends the row. The row's length is the answer, in n log n time.

Look back, take the best, add one. That's Longest Increasing Subsequence.