Number of Longest Increasing Subsequence - Problem

Given an integer array nums, return the number of longest increasing subsequences.

Notice that the sequence has to be strictly increasing.

A subsequence is a sequence derived from an array by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,6,7,9,4,10,5,6]
Output: 2
💡 Note: The longest increasing subsequences are [1,3,6,7,9] and [1,3,6,7,10], both have length 5. So there are 2 longest increasing subsequences.
Example 2 — Single Element Repeated
$ Input: nums = [2,2,2,2,2]
Output: 5
💡 Note: Each single element forms a valid increasing subsequence of length 1. Since there are 5 elements, there are 5 longest increasing subsequences.
Example 3 — Strictly Decreasing
$ Input: nums = [5,4,3,2,1]
Output: 5
💡 Note: No increasing subsequence of length > 1 exists. Each single element is a longest increasing subsequence, giving us 5 subsequences of length 1.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Number of Longest Increasing Subsequences INPUT nums array: 1 3 6 7 9 4 10 5 6 indices: 0 to 8 Two Longest Subsequences: LIS 1: 1,3,6,7,9,10 Length = 6 LIS 2: 1,3,4,5,6,10 Length = 6 Input Array: [1,3,6,7,9,4,10,5,6] ALGORITHM STEPS 1 Initialize Arrays length[i]=1, count[i]=1 2 For each i, check j<i if nums[j]<nums[i] 3 Update length/count Track max and count 4 Sum all max counts Return total count DP Arrays (final state): len[]: 1 2 3 4 5 3 6 4 5 cnt[]: 1 1 1 1 1 1 2 1 1 Update Logic: if len[j]+1 > len[i]: len[i]=len[j]+1, cnt[i]=cnt[j] FINAL RESULT Maximum LIS Length = 6 Found 2 Paths of Length 6: Path 1: 1 --> 3 --> 6 --> 7 --> 9 --> 10 Path 2: 1 --> 3 --> 4 --> 5 --> 6 --> 10 OUTPUT 2 OK - Two LIS found! Key Insight: Use two DP arrays: length[i] stores LIS length ending at i, count[i] stores number of such sequences. When updating, if same length found, ADD counts (not replace). Final answer: sum counts where length = max. Time: O(n^2) | Space: O(n) TutorialsPoint - Number of Longest Increasing Subsequence | Optimal DP Solution
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
89.0K Views
Medium Frequency
~25 min Avg. Time
2.2K 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