Python 0673.py
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
length = [ 0 ] * len(nums)
combos = [ 0 ] * len(nums)
for i in range(len(nums)):
length[i] = 1
combos[i] = 1
for j in range(0, i):
if nums[j] < nums[i]:
longer = length[j] + 1
if length[i] == longer:
combos[i] += combos[j]
elif length[i] < longer:
length[i] = longer
combos[i] = combos[j]
longest = max(length)
result = 0
for i in range(len(combos)):
if length[i] == longest:
result += combos[i]
return result
Difficulty
and has an acceptance rate of about 52% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Indexed Tree
- Dynamic Programming
- Segment Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the number of longest increasing subsequences (LIS) within a list of integers. It employs a dynamic-programming strategy that records, for each position, both the length of the longest increasing subsequence ending at that index and the count of distinct subsequences that achieve that length. By scanning the input once for each element and then aggregating the counts of those positions that attain the global maximum length, the algorithm returns the total number of longest increasing subsequences.
Initialization of State
At the start of the method two auxiliary arrays are created, each sized to the input list.
length = [0] * len(nums)
combos = [0] * len(nums)
length[i] will hold the length of the longest increasing subsequence that ends at index i.
combos[i] will hold the number of such subsequences.
Both arrays are subsequently populated inside the outer loop, guaranteeing that every index begins with a baseline subsequence consisting solely of the element itself.
Main Dynamic-Programming Loop
The core of the algorithm consists of a nested loop. The outer loop iterates over each element i in the input. For each i the baseline values are set:
length[i] = 1
combos[i] = 1
The inner loop examines every preceding index j (0 ≤ j < i). When the value at j is smaller than the value at i, the subsequence ending at j can be extended. The candidate length is computed as:
longer = length[j] + 1
Three situations are considered:
- If the candidate length equals the current recorded length for
i, the count of subsequences is increased by the number of ways to reachj:
if length[i] == longer:
combos[i] += combos[j]
- If the candidate length exceeds the current recorded length, the algorithm updates both the length and the count to reflect the newly discovered longer subsequence:
elif length[i] < longer:
length[i] = longer
combos[i] = combos[j]
Through this mechanism the algorithm simultaneously tracks the optimal length and aggregates all distinct ways to achieve it for each position.
Determination of Global Maximum Length
After processing all pairs, the longest length among all positions is extracted:
longest = max(length)
Because each entry in length reflects the best subsequence ending at that index, the maximum represents the length of any longest increasing subsequence in the entire array.
Accumulation of Result
A final pass over the combos array sums the counts of those positions whose length matches the global maximum:
result = 0
for i in range(len(combos)):
if length[i] == longest:
result += combos[i]
The variable result therefore holds the total number of distinct longest increasing subsequences, which is returned as the method’s output.
Edge Cases Handled
When the input contains a single element, the outer loop runs once, initializing length[0] and combos[0] to one. The inner loop has no iterations, leaving the longest length as one and the result as one, correctly reflecting that the sole element forms the only longest increasing subsequence.
If the input is strictly decreasing, each element can only form a subsequence of length one. The inner loop never satisfies the condition nums[j] < nums[i], so every length[i] remains one and every combos[i] stays one. The maximum length is one, and the final aggregation sums all combos[i], yielding a result equal to the number of elements, which matches the expectation that each element individually constitutes a longest increasing subsequence.
When duplicate values appear, the strict inequality nums[j] < nums[i] prevents equal values from extending a subsequence. Consequently, subsequences that would otherwise be ambiguous due to equal elements are correctly excluded, ensuring that only strictly increasing sequences are counted.
The algorithm also gracefully handles cases where multiple distinct paths lead to the same length. By adding combos[j] whenever an alternative path of equal length is discovered, it accumulates all valid combinations without double-counting.
Performance Optimizations
The implementation avoids the overhead of auxiliary data structures such as dictionaries or nested objects by using plain integer lists for both length and count tracking. This choice reduces memory allocation and improves cache locality during the nested iteration.
By initializing each entry to the base case inside the outer loop, the code eliminates the need for a separate preprocessing pass. The inner loop performs only the essential comparison and arithmetic operations, and the conditional branches are arranged to minimize unnecessary assignments: the count is updated only when a longer subsequence is found, otherwise it is merely incremented.
The final aggregation step iterates over the combos list a single time, reusing the previously computed length values to filter relevant entries. This avoids a second pass over the original input array and leverages the already available state.
Overall, the design keeps the algorithm’s runtime tight by limiting each element’s work to a straightforward scan of its predecessors and by maintaining all necessary information in compact, mutable arrays.
ELI5 - Simplified Explanation
Think of a row of growing flowers along a garden path, where each flower has a specific height. This computer program helps count how many different ways one can pick a group of flowers that get taller every step of the way.
First, two long paper strips are laid out to keep track of information. One strip remembers the height of the tallest group of flowers ending at each spot, and the other strip counts how many different ways those tall groups can be formed.
The program walks along the row of flowers one by one. For every flower, it looks back at all the previous ones to see which ones are shorter. When a shorter flower is found, the program checks if adding the current flower creates a new personal record for the tallest group. If the record is tied, the count of ways is added together. If a new, taller record is set, the count is refreshed to represent this new, superior path.
After checking every flower in the row, the program looks at the height strip to find the very biggest number hidden there. Finally, it adds up all the ways that lead to that specific maximum height to see how many successful paths exist in total.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fengvyi | C++ | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fengvyi | C++ | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 300: Longest Increasing Subsequence
- problem 674: Longest Continuous Increasing Subsequence
- problem 2407: Longest Increasing Subsequence II
Solved On The Same Day
- problem 71: Simplify Path
- problem 309: Best Time to Buy and Sell Stock with Cooldown
- problem 516: Longest Palindromic Subsequence
- problem 712: Minimum ASCII Delete Sum for Two Strings
- problem 714: Best Time to Buy and Sell Stock with Transaction Fee
- problem 740: Delete and Earn
- problem 931: Minimum Falling Path Sum
- problem 2483: Minimum Penalty for a Shop
- problem 188: Best Time to Buy and Sell Stock IV
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality