Number of Longest Increasing Subsequence
LeetCode 673 · Medium · solution, intuition & step-by-step walkthrough
Longer ⇒ copy the count; equal ⇒ add the count.
This is how I solved Number of Longest Increasing Subsequence (LeetCode 673), a medium problem from the LIS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Alongside the LIS length ending at each index, also count how many sequences reach that length. When an earlier element gives a strictly longer run, its count replaces ours; when it ties, its count adds to ours.
Approach
- 1
dp[i] = LIS length ending at i; count[i] = number of such sequences.
- 2
For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i].
- 3
Longer: set dp[i] and copy count[j]. Equal: add count[j].
- 4
Sum count[i] over all i whose dp[i] equals the overall max.
How I solved it
LIS with countsPythonO(n²) time · O(n) space
class Solution:
#1,3,5,4,7
def findNumberOfLIS(self, nums: List[int]) -> int:
dp=[1]*len(nums)
count=[1]*len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i]>nums[j]:
if dp[j]+1>dp[i]:
dp[i]=dp[j]+1
count[i]=count[j] #copy
elif dp[j]+1==dp[i]:
count[i]+=count[j] #add
lis=max(dp)
result=0
for i in range(len(nums)):
if dp[i]==lis:
result+=count[i]
return resultNumber of Longest Increasing Subsequence — FAQ
What is the intuition behind Number of Longest Increasing Subsequence?
Alongside the LIS length ending at each index, also count how many sequences reach that length. When an earlier element gives a strictly longer run, its count replaces ours; when it ties, its count adds to ours.
How do you solve Number of Longest Increasing Subsequence (LeetCode 673)?
1. dp[i] = LIS length ending at i; count[i] = number of such sequences. 2. For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i]. 3. Longer: set dp[i] and copy count[j]. Equal: add count[j]. 4. Sum count[i] over all i whose dp[i] equals the overall max.
What is the time and space complexity of Number of Longest Increasing Subsequence?
Time: O(n²). Space: O(n). (Accepted approach: LIS with counts.)
What are common mistakes in Number of Longest Increasing Subsequence?
Sum counts over every index that reaches the max length, not just the last one.