Longest Increasing Subsequence

Find how many numbers, kept in their order, can be picked from an array so that each one is larger than the last.

Given an array of integers nums, return the length of its longest strictly increasing subsequence. A subsequence keeps some of the numbers in their original order and drops the rest, so the kept numbers do not have to sit next to each other. Strictly increasing means each kept number is larger than the one kept before it.

Example 1
Input: nums = [10, 9, 2, 5, 3, 7, 101, 18]
Output: 4
Explanation: one longest choice is [2, 3, 7, 101].
Example 2
Input: nums = [0, 1, 0, 3, 2, 3]
Output: 4
Example 3
Input: nums = [7, 7, 7, 7]
Output: 1
Solution

The Idea

Read the numbers of Example 1 from left to right, like a row of steps, and keep only steps that go up. Keeping 2, 5, 7 and 101 works, and so does 2, 3, 7 and 18. Keeping 10 and then 101 works too, but that climb stops after two steps. No choice of five numbers keeps going up, so the answer is 4.

Example 3 shows why the word strictly matters. In [7, 7, 7, 7], a second 7 is not higher than the first, so the longest climb is a single 7, and the answer is 1.

Each number can be kept or dropped, so eight numbers give 28 = 256 different subsequences, and every extra number doubles that count. How can we find the longest climb without trying them all?

Ask a smaller question for each position instead: how long is the longest increasing subsequence that ends exactly at this number? Take the 7 at index 5, counting positions from 0. In a climb that ends at 7, the number just before 7 is earlier and smaller, so it is 2, 5 or 3. If we already know the longest climb that ends at each of those three, 7 simply adds one step to the best of them. Look at the picture below.

The row nums holds 10, 9, 2, 5, 3, 7, 101, 18 and the row dp: longest ending here holds 1, 1, 1, 2, 2, 3, 4, 4. For 7 at index 5, the smaller values before it, 2, 5 and 3, have 1, 2 and 2, so dp[5] = 1 + 2 = 3.

The row labelled "nums" is Example 1, and under each number, the row labelled "dp: longest ending here" holds the answer to the smaller question. The teal boxes are the smaller values before 7: 2, 5 and 3, with 1, 2 and 2 below them. The best is 2, from 5 or 3, so the orange box under 7 holds 1 + 2 = 3, the climb 2, 3, 7.

Further right, 101 builds on that 3 and gets 4, and so does 18. The longest climb can end at any number, so the answer to the whole problem is the largest entry in the row, 4.

So each entry is worked out from entries to its left that are already known. Here the answers for all eight positions go in one row named dp, and each one is built from answers further left. Solving a problem by storing the answers to smaller questions like these and building on them is called dynamic programming. In words, dp[i] is the length of the longest increasing subsequence that ends at nums[i].

Solution Approach

Turning that idea into code means settling three things: what each entry of dp starts at, how it grows from the entries before it, and where the answer is found. Optionally, a fourth question: is there a faster method?

The starting value of each entry

What is dp[i] before any earlier number is considered? The number nums[i] on its own is already a climb of length 1, so every entry starts at 1. In the picture, 10, 9 and 2 keep that 1, because no smaller number comes before any of them.

Growing an entry from earlier entries

Which earlier entries can nums[i] build on? Call an earlier position j. Every j before i with nums[j] < nums[i] qualifies: adding nums[i] to the climb that ends at nums[j] makes it dp[j] + 1 long. So dp[i] becomes the largest dp[j] + 1 over those positions, or stays 1 if there are none.

Filling the row from left to right means every dp[j] is final by the time dp[i] needs it. The comparison must be strictly less than: with <=, each 7 in Example 3 would build on the 7 before it.

Where the answer is

Why not simply return the last entry? The longest climb does not have to end at the last number. In [1, 2, 3, 0], the climb 1, 2, 3 has length 3, but the 0 at the end starts a climb of its own of length 1. So the answer is the largest entry anywhere in dp.

Optional: a faster method with the smallest tails

Is there a way to avoid looking back at every earlier number? Keep a sorted list called tails instead, where the entry at position k is the smallest number that can end a climb of length k + 1 found so far. A smaller end is better, because more later numbers can follow it.

For each new number, find the first entry in tails that is not smaller than it. If there is one, the new number replaces it; if not, the new number goes on the end. In Example 1, 10 starts the list, then 9 and 2 each replace that single entry, leaving [2]. Then 5 goes on the end, [2, 5], and 3 replaces 5, giving [2, 3].

Next, 7 and 101 go on the end, [2, 3, 7, 101], and 18 replaces 101, giving [2, 3, 7, 18]. The length of tails, 4, is the answer. Because the list stays sorted, the right entry can be found by repeatedly halving the range, so a list of 1,000 entries needs about 10 checks, not 1,000.

Java Solution

The method endingAt fills the table, and lengthOfLIS picks the answer from it, in these steps:

  1. First, endingAt creates the table dp with new int[nums.length], one entry per number.
  2. A loop moves i from left to right and sets dp[i] = 1, the climb of nums[i] on its own.
  3. Inside, a second loop moves j over the positions before i. When nums[j] < nums[i], dp[i] becomes dp[j] + 1 if that is larger.
  4. When both loops are done, endingAt returns the filled dp.
  5. lengthOfLIS walks over that table, keeps the largest entry in best, which starts at 0, and returns best.

The main method prints the table and the answer for the three examples, a falling array, an array whose longest climb ends before its last number, and an empty array.

Java
import java.util.Arrays;

public class LongestIncreasingSubsequence {

    // dp[i] = length of the longest increasing subsequence that ends at nums[i]
    public static int[] endingAt(int[] nums) {
        int[] dp = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            dp[i] = 1;                              // nums[i] on its own
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {            // nums[i] can follow nums[j]
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
        }
        return dp;
    }

    public static int lengthOfLIS(int[] nums) {
        int best = 0;
        for (int length : endingAt(nums)) {
            best = Math.max(best, length);          // the longest may end anywhere
        }
        return best;
    }

    static void show(int[] nums) {
        System.out.println("nums " + Arrays.toString(nums) + ", dp "
                + Arrays.toString(endingAt(nums)) + ", answer " + lengthOfLIS(nums));
    }

    public static void main(String[] args) {
        show(new int[] {10, 9, 2, 5, 3, 7, 101, 18});
        show(new int[] {0, 1, 0, 3, 2, 3});
        show(new int[] {7, 7, 7, 7});
        show(new int[] {5, 4, 3, 2, 1});
        show(new int[] {1, 2, 3, 0});
        show(new int[] {});
    }
}

Running it prints:

Output
nums [10, 9, 2, 5, 3, 7, 101, 18], dp [1, 1, 1, 2, 2, 3, 4, 4], answer 4
nums [0, 1, 0, 3, 2, 3], dp [1, 2, 1, 3, 3, 4], answer 4
nums [7, 7, 7, 7], dp [1, 1, 1, 1], answer 1
nums [5, 4, 3, 2, 1], dp [1, 1, 1, 1, 1], answer 1
nums [1, 2, 3, 0], dp [1, 2, 3, 1], answer 3
nums [], dp [], answer 0

The table for Example 1, [1, 1, 1, 2, 2, 3, 4, 4], matches the picture, with the 3 under 7. In Example 2, the last 3 gets 4 from the climb 0, 1, 2, 3.

For [7, 7, 7, 7] every entry stays 1, because the check is nums[j] < nums[i]. With <= in its place, the same input gives 4. The falling array [5, 4, 3, 2, 1] also gets all 1s, since no number has a smaller one before it.

Look at the line for [1, 2, 3, 0]: its last entry is 1, yet the answer is 3, the entry under 3. The empty array gives an empty table, so best stays 0.

Complexity

The work is the two loops that fill dp, and one more pass to find its largest entry.

  • Time: O(n²), because each of the n numbers looks back at every number before it, about n²/2 comparisons, while the pass for the largest entry adds only n steps.
  • Space: O(n), because dp stores one climb length for each of the n numbers.

The method with tails brings the time down to O(n log n) with the same O(n) space. To count how many different longest climbs there are, see Number of Longest Increasing Subsequences.