Number of Longest Increasing Subsequences

Count how many longest strictly increasing subsequences an array has, by tracking the best length and its number of ways at each position.

Given an integer array nums, return how many of its longest strictly increasing subsequences there are. A subsequence keeps some of the numbers in their original order, possibly skipping others in between. Strictly increasing means each number is bigger than the one before it. Two subsequences count as different when they use different positions, even if their values are the same.

Example 1
Input: nums = [1, 3, 5, 4, 7]
Output: 2
Explanation: [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2
Input: nums = [2, 2, 2, 2, 2]
Output: 5
Explanation: the longest length is 1, and each of the five 2s is one such subsequence.
Solution

The Idea

Picture the numbers 1, 3, 5, 4 and 7 as stepping stones across a stream, read from left to right. You cross by stepping on some of them in order, and each stone you step on must be higher than the last one. You may skip stones, but never go back.

The longest crossings in Example 1 step on four stones: 1, 3, 5, 7 and 1, 3, 4, 7. Each crossing is a strictly increasing subsequence, and two of them have the longest length, so the answer is 2. In Example 2 no stone is higher than another, so every crossing is a single stone, and there are five of those.

Five stones are easy to check by hand, but a longer array has far too many crossings to write out. How can we count the longest ones without listing them?

Look at where a crossing ends. Every increasing subsequence that ends at 7 is either 7 alone, or one ending at a smaller number to the left of 7, with 7 added. So for each number it is enough to know two things: the length of the longest increasing subsequence ending there, and how many subsequences of that length end there.

Look at the picture below. The row labelled "longest increasing subsequence ending here" reads 1, 2, 3, 3, 4. The row labelled "how many of that length end here" reads 1, 1, 1, 1, 2.

For nums 1, 3, 5, 4, 7, the longest increasing subsequence ending at each number has length 1, 2, 3, 3, 4, and 1, 1, 1, 1, 2 subsequences of that length end there. 7 extends both 5 and 4, each of length 3 reached in 1 way, so 7 gets length 4 in 2 ways.

Follow the arrows into 7. Both 5 and 4 are smaller than 7, and each ends an increasing subsequence of length 3 that is reached in 1 way: 1, 3, 5 and 1, 3, 4. Adding 7 to either gives length 4, so 7 gets length 4, reached in 1 + 1 = 2 ways. No number has a longer length, so the answer is 2.

So the two numbers at 7 come straight from the numbers already worked out for 5 and 4. Filling both rows from left to right, each entry built from entries to its left instead of listing subsequences again, is called dynamic programming.

Solution Approach

Turning that idea into code means comparing it with listing every subsequence, then settling three things: the starting values of the two rows, how a smaller earlier number updates them, and how the answer is added up.

Listing every subsequence

Why not write out every increasing subsequence and count the longest? Each number is either in a subsequence or left out, so five numbers give 25 = 32 choices, and thirty numbers already give over a billion. The two rows need only one look back over the earlier numbers for each number.

Starting values

What does a number have before it looks to its left? On its own, it is an increasing subsequence of length 1, and there is exactly one of it. So both rows start at 1 at every position. In Example 2, no 2 is bigger than an earlier 2, so both rows stay at 1 everywhere.

Extending from a smaller earlier number

What happens when an earlier number is smaller than the current one? Each of its longest subsequences can be extended by the current number, giving a length one more than its own. Compare that length with the best length found so far at the current number:

  • Longer: it is the new best length. The count found so far belonged to shorter subsequences, so it is replaced by the earlier number's count.
  • Equal: these are more ways to reach the same length, so the earlier number's count is added.
  • Shorter: nothing changes, because those subsequences are not the longest ones ending here.

Take the 7 in Example 1. It looks at 1, 3 and 5 in turn, and each one raises its length, ending at 4 with the count 1 copied from 5. Then 4 also gives length 4, an equal length, so its count of 1 is added and 7 ends with 2.

Adding up the answer

Where do the longest subsequences end? Not always at one number. In Example 2 every 2 ends a longest subsequence of length 1, so the answer adds the counts at all five positions. So keep the longest length seen so far, and a running total of the counts at positions that reach it. A longer length restarts the total, and an equal one adds to it.

Java Solution

The method findNumberOfLIS works in these steps:

  1. First, create two arrays as long as nums: length, where length[i] is the length of the longest increasing subsequence ending at nums[i], and count, where count[i] is how many subsequences of that length end there. Two variables start at 0: longest, the longest length seen so far, and total, the running total of counts at that length.
  2. An outer loop moves i over the array. It sets length[i] and count[i] to 1, for nums[i] on its own.
  3. Inside it, a second loop moves j over the positions before i. When nums[j] < nums[i], the extension has length length[j] + 1. If that beats length[i], it becomes length[i] and count[i] becomes count[j]. If it equals length[i], count[j] is added to count[i].
  4. After the inner loop, compare length[i] with longest. A bigger length becomes longest and total restarts at count[i]. An equal length adds count[i] to total.
  5. When the outer loop ends, the method prints both arrays, so the output shows the two rows, and returns total.

The main method runs both examples, an array where a count of 2 is passed on, an array whose longest subsequences end at two different numbers, a decreasing array and an empty one.

Java
import java.util.Arrays;

public class NumberOfLongestIncreasingSubsequences {

    public static int findNumberOfLIS(int[] nums) {
        int n = nums.length;
        int[] length = new int[n];   // longest increasing subsequence ending at i
        int[] count = new int[n];    // how many of that length end at i
        int longest = 0;
        int total = 0;
        for (int i = 0; i < n; i++) {
            length[i] = 1;           // nums[i] on its own
            count[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    if (length[j] + 1 > length[i]) {          // a longer way: take j's count
                        length[i] = length[j] + 1;
                        count[i] = count[j];
                    } else if (length[j] + 1 == length[i]) {  // another way to the same length
                        count[i] += count[j];
                    }
                }
            }
            if (length[i] > longest) {                        // a new longest length
                longest = length[i];
                total = count[i];
            } else if (length[i] == longest) {                // more of the longest length
                total += count[i];
            }
        }
        System.out.println("  length = " + Arrays.toString(length));   // the two tables
        System.out.println("  count  = " + Arrays.toString(count));
        return total;
    }

    public static void main(String[] args) {
        int[][] tests = {
            {1, 3, 5, 4, 7},
            {2, 2, 2, 2, 2},
            {1, 2, 4, 3, 5, 4, 7, 2},
            {1, 1, 2, 2},
            {5, 4, 3, 2, 1},
            {}
        };
        for (int[] nums : tests) {
            System.out.println(Arrays.toString(nums));
            System.out.println("  answer = " + findNumberOfLIS(nums));
        }
    }
}

Running it prints:

Output
[1, 3, 5, 4, 7]
  length = [1, 2, 3, 3, 4]
  count  = [1, 1, 1, 1, 2]
  answer = 2
[2, 2, 2, 2, 2]
  length = [1, 1, 1, 1, 1]
  count  = [1, 1, 1, 1, 1]
  answer = 5
[1, 2, 4, 3, 5, 4, 7, 2]
  length = [1, 2, 3, 3, 4, 4, 5, 2]
  count  = [1, 1, 1, 1, 2, 1, 3, 1]
  answer = 3
[1, 1, 2, 2]
  length = [1, 1, 2, 2]
  count  = [1, 1, 2, 2]
  answer = 4
[5, 4, 3, 2, 1]
  length = [1, 1, 1, 1, 1]
  count  = [1, 1, 1, 1, 1]
  answer = 5
[]
  length = []
  count  = []
  answer = 0

For [1, 3, 5, 4, 7], the length line, [1, 2, 3, 3, 4], and the count line, [1, 1, 1, 1, 2], are the two rows of the picture, and the answer is 2.

The array [1, 2, 4, 3, 5, 4, 7, 2] shows a count being passed on. The 5 at index 4 has count 2, from 1, 2, 4, 5 and 1, 2, 3, 5. The 7 at index 6 copies that 2 from 5 and adds 1 from the 4 at index 5, so its count is 3, the answer. A version that sets count[i] to 1 on a longer length, instead of copying count[j], returns 2 for this array, because 7 then forgets that 5 was reached in two ways.

For [1, 1, 2, 2] the answer is 4: each 2 can follow either 1, so both 2s have count 2, and total adds them. In [5, 4, 3, 2, 1] no number is bigger than an earlier one, so each number is a longest subsequence on its own and the answer is 5. The empty array has nothing to count, and the answer is 0.

Complexity

The work is the two loops: each number looks back once at every number before it.

  • Time: O(n²), because each of the n numbers checks all the numbers to its left, about n²/2 comparisons in all, each followed by at most one update.
  • Space: O(n), because the length and count arrays hold one entry for each number in nums.

Finding only the longest length, without counting the subsequences, is covered in Longest Increasing Subsequence.