Number of Longest Increasing Subsequence - Problem

Given an integer array nums, find the longest increasing subsequence and return how many such sequences exist.

A subsequence is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. The sequence must be strictly increasing.

Example: In array [1, 3, 5, 4, 7], there are two longest increasing subsequences of length 4: [1, 3, 5, 7] and [1, 3, 4, 7], so the answer is 2.

This problem combines the classic Longest Increasing Subsequence challenge with a counting twist - you need to track not just the length, but also how many ways you can achieve that optimal length.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,3,5,4,7]
โ€บ Output: 2
๐Ÿ’ก Note: Two longest increasing subsequences of length 4: [1,3,5,7] and [1,3,4,7]
example_2.py โ€” Single Element
$ Input: [2,2,2,2,2]
โ€บ Output: 5
๐Ÿ’ก Note: All elements are equal, so each single element forms a LIS of length 1. There are 5 such subsequences.
example_3.py โ€” Strictly Increasing
$ Input: [1,2,3,4,5]
โ€บ Output: 1
๐Ÿ’ก Note: Only one longest increasing subsequence: [1,2,3,4,5] with length 5

Visualization

Tap to expand
Number of Longest Increasing SubsequencesInput Array: [1, 3, 5, 4, 7]13547Dynamic Programming Process:Position 0 (value=1): length=1, count=1Position 1 (value=3): extends from 0, length=2, count=1Position 2 (value=5): extends from 0,1, length=3, count=1Position 3 (value=4): extends from 0,1, length=3, count=1Position 4 (value=7): extends from 2,3, length=4, count=2Two Longest Increasing Subsequences:1357โ† First LIS1347โ† Second LISAnswer: 2
Understanding the Visualization
1
Initialize
Each block can form a tower of height 1 by itself
2
Extend Towers
For each new block, check which existing towers it can extend
3
Update Counts
Add up the number of ways to build towers of the new height
4
Find Maximum
Identify the tallest towers and count all ways to build them
Key Takeaway
๐ŸŽฏ Key Insight: Use dynamic programming to track both the maximum length and count of increasing subsequences ending at each position, then sum up counts for positions with the global maximum length.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log n)

O(n log n) for sorting and coordinate compression, O(n log n) for segment tree operations

n
2n
โšก Linearithmic
Space Complexity
O(n)

Space for coordinate mapping and segment tree structure

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 2000
  • -106 โ‰ค nums[i] โ‰ค 106
  • The subsequence must be strictly increasing
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 25
67.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen