Number of Longest Increasing Subsequence (LeetCode 673): Solution and Explanation

Medium
Array
Dynamic Programming
Binary Indexed Tree
Segment Tree

Find the length of the longest strictly increasing subsequence, then count how many different subsequences reach that length.

Intuition

The classic LIS DP asks, for every index i, how long the best increasing subsequence ending at i can be. It looks back at every earlier j with a smaller value and extends the best of them.

Counting needs one more number per index: how many subsequences reach that best length at i. Every one of them is a best subsequence ending at some smaller j, with nums[i] stuck on the end. So count[i] is the sum of count[j] over the j that give the best length.

While scanning j you do not know the final best length yet. If a j gives a strictly longer run, the old count is useless and you replace it with count[j]. If a j ties the current best, its subsequences are new ones of the same length, so you add count[j].

Approach: LIS DP with counts

  1. Set length[i] = 1 and count[i] = 1 for every index: each element alone is one subsequence.
  2. For each i, scan every j < i with nums[j] < nums[i].
  3. If length[j] + 1 > length[i], set length[i] = length[j] + 1 and count[i] = count[j].
  4. Else if length[j] + 1 == length[i], do count[i] += count[j].
  5. Let longest = max(length) and return the sum of count[i] over all i with length[i] == longest.

Step-by-step example

nums = [1,3,5,4,7]
  1. Index 0 (1): nothing before it. length = 1, count = 1.
  2. Index 1 (3): extends 1, so length = 2, count = 1. Index 2 (5): best via 3, length = 3, count = 1.
  3. Index 3 (4): 5 is not smaller, so the best is again via 3: length = 3, count = 1.
  4. Index 4 (7): via 5 gives length 4 with count 1, then via 4 ties at length 4 and adds its 1, so count = 2.
  5. The longest length is 4, reached only at index 4, so the answer is 2: [1,3,5,7] and [1,3,4,7].

Code: Python, Java, C++

1class Solution:
2    def findNumberOfLIS(self, nums: List[int]) -> int:
3        n = len(nums)
4        length = [1] * n
5        count = [1] * n
6        for i in range(n):
7            for j in range(i):
8                if nums[j] < nums[i]:
9                    if length[j] + 1 > length[i]:
10                        length[i] = length[j] + 1
11                        count[i] = count[j]
12                    elif length[j] + 1 == length[i]:
13                        count[i] += count[j]
14        longest = max(length)
15        return sum(c for l, c in zip(length, count) if l == longest)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

For each of the n indices you look back at every earlier index once.

Space

O(n)

Two arrays of length n, one for lengths and one for counts.

Other approaches

Segment tree or Fenwick tree over values (time O(n log n), space O(n))

Compress the values, then for each nums[i] query the best (length, count) pair among all smaller values and insert the result. Merging two pairs keeps the longer length and adds counts on ties.

Patience sorting buckets with prefix sums (time O(n log n), space O(n))

Extend the binary search LIS: each pile keeps its tops with running count sums, and a binary search inside the previous pile finds how many smaller tops can be extended. Fast but fiddly to get right.

Common mistakes

  • Adding count[j] whenever nums[j] < nums[i]. Only the j that give the best length count; shorter runs ending at i are not longest.
  • Forgetting to reset the count when a strictly longer run appears. Without the reset, counts from the old, shorter length leak in.
  • Returning count[n-1] or the count at the argmax. Several indices can end a longest subsequence, and all of their counts must be summed.
  • Using <= instead of <. Equal values cannot both appear in a strictly increasing subsequence, which is why [2,2,2,2,2] gives 5 and not 1.

Frequently asked questions

Why does a tie add counts instead of keeping the maximum?

Two different j with the same best length lead to different sets of indices, so they are different subsequences. Each contributes all of its own ways.

Can the binary search LIS trick be used directly?

Not by itself. It only tracks one smallest tail per length and throws away the information about how many ways reach it. You need extra bookkeeping, such as per-pile prefix sums or a Fenwick tree, to count.

What does the answer look like for a strictly decreasing array?

Every element is its own longest increasing subsequence of length 1, so the answer is n.