← Whiteboard questions

Longest Increasing Subsequence

Longest strictly rising subsequence, in order, gaps allowed

DSA, Medium, 1-D DP

Which structure or algorithm, and what does it cost.

A list nums holds whole numbers. A rising subsequence is a choice of values that keeps their original order and gets strictly larger each time. The values need not be next to each other. Return the length of the longest rising subsequence. An empty list gives 0.

Examples

Input nums = [3, 1, 4, 1, 5, 9, 2, 6]
Output 4
Why one longest choice is 1, 4, 5, 9. No choice of five values keeps rising.
Input nums = [5, 5, 5, 5]
Output 1
Why equal values are not strictly larger, so one value is the longest choice.
Input nums = []
Output 0
Why there are no values, so no subsequence.

Constraints

Your answer must contain

Target Aim for O(n log n) time and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look at one value as the last of a rising choice. How long can a rising choice that ends here be, if you know the answer for earlier values?

Hint 2 the approach

The table method takes quadratic time, too slow for 100,000 values. For each length, which ending value would be the most useful to remember?

Hint 3 the key step

For each length, keep the smallest value that can end a rising choice of that length. These values stay sorted, so binary search finds where each new value goes.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every subset of positions, keep those that rise, and take the longest. There are 2^n subsets, so this only works for about 20 values.

Better method

Dynamic programming. Let best[i] be the length of the longest rising choice that ends at position i. It is 1 plus the largest best[j] over earlier positions j with a smaller value, or just 1 if there is none. The answer is the largest best[i]. This is O(n^2) time and O(n) memory, too slow for 100,000 values.

Best method

Keep a list called tails. Entry k holds the smallest value that can end a rising choice of length k + 1. The list is always sorted, because a smaller ending for a longer choice would also end a shorter one. For each new value x, binary search for the first entry that is at least x. If there is none, x extends the longest choice, so append it. Otherwise replace that entry with x, because a smaller ending is never worse. The answer is the length of tails at the end. The list is not itself the subsequence. It only tracks the best endings. Searching for "at least x" instead of "larger than x" stops equal values from counting twice.

Hand trace

Run on [3, 1, 4, 1, 5, 9, 2, 6]. Value 3: tails is empty, so append. Tails [3]. Value 1: the first entry at least 1 is 3, so replace it. Tails [1]. Value 4: none is at least 4, so append. Tails [1, 4]. Value 1: the first entry at least 1 is 1, so it is replaced by 1. Tails [1, 4]. Value 5: append. Tails [1, 4, 5]. Value 9: append. Tails [1, 4, 5, 9]. Value 2: the first entry at least 2 is 4, so replace it. Tails [1, 2, 5, 9]. Value 6: the first entry at least 6 is 9, so replace it. Tails [1, 2, 5, 6]. The length is 4.

Code

from bisect import bisect_left
def length_of_lis(nums):
    tails = []                      # tails[k] = smallest end of a rising choice of length k + 1
    for x in nums:
        k = bisect_left(tails, x)
        if k == len(tails):
            tails.append(x)
        else:
            tails[k] = x
    return len(tails)

Time and memory

O(n log n) time, because each of the n values needs one binary search. O(n) memory for tails.

Common mistakes

  • Treating tails as the answer sequence. After the value 2 it reads [1, 2, 5, 9], and 2 comes after 9 in the input, so it is not a subsequence.
  • Searching for the first entry larger than x. Equal values then extend the list, and [5, 5, 5, 5] gives 4 instead of 1.
  • Mixing up a subsequence with a subarray. The chosen values do not have to be next to each other.

Related problems

More 1-D DP problems
Longest Increasing Subsequence: walkthrough and solution