Python 0491.py
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
todo = [ [ nums[0] ] ]
for n in nums[1:]:
next = todo + [ [ n ] ]
for t in todo:
longer = t + [ n ]
if n >= t[-1] and longer not in next:
next.append(longer)
todo = next
return [ t for t in todo if len(t) >= 2 ]
Difficulty
and has an acceptance rate of about 61% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- Hash Table
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 defines a class Solution with a method findSubsequences that receives a list of integers and returns all increasing subsequences of length at least two. The algorithm builds subsequences incrementally by iterating through the input list and extending previously generated sequences when the monotonic condition is satisfied. Duplicate subsequences are avoided by checking membership before insertion.
Key Steps
The method begins by initializing a working list todo that contains a single-element subsequence consisting of the first number in the input. This establishes the base case for the iterative construction.
todo = [ [ nums[0] ] ]
The core of the algorithm is a loop that processes each remaining element n in the input list. For each element, a new list next is created that initially contains all subsequences from the previous iteration (todo) and a new one-element subsequence [n]. This ensures that every element can start a new potential subsequence.
for n in nums[1:]:
next = todo + [ [ n ] ]
Inside the same loop, the code iterates over each existing subsequence t in todo. For each t, it constructs a candidate longer subsequence longer by appending the current element n. The monotonic condition n >= t[-1] guarantees that the new subsequence remains non-decreasing. If the condition holds and the candidate is not already present in next, it is appended to next. This step both extends valid subsequences and prevents duplicate entries.
for t in todo:
longer = t + [ n ]
if n >= t[-1] and longer not in next:
next.append(longer)
After processing all existing subsequences for the current element, the working list todo is updated to the newly built list next. This prepares the algorithm for the next iteration, carrying forward all valid subsequences generated so far.
todo = next
Finally, the method filters the accumulated subsequences, returning only those whose length is at least two. This satisfies the problem requirement that trivial one-element sequences be excluded.
return [ t for t in todo if len(t) >= 2 ]
Edge Cases Handled
The algorithm gracefully handles input lists containing a single element. In such a scenario, the initial todo contains one one-element subsequence, the loop over nums[1:] does not execute, and the final list comprehension filters out the sole element, resulting in an empty list as expected.
When the input list includes repeated values, the condition n >= t[-1] permits equal numbers to be part of a non-decreasing subsequence. The explicit check longer not in next prevents the same subsequence from being added multiple times, even if different paths in the iteration could generate identical sequences.
If the input list is empty, attempting to access nums[0] would raise an exception; however, the problem specification typically guarantees at least one element, and the code assumes this precondition. Within the defined contract, the method correctly returns an empty list when no qualifying subsequences exist, such as when all numbers are strictly decreasing.
Performance Optimizations
The implementation avoids recomputing the entire set of subsequences from scratch on each iteration. By reusing the todo list and only extending existing sequences that satisfy the monotonic condition, the algorithm reduces unnecessary work. The use of next = todo + [ [ n ] ] creates a shallow copy of the current subsequences while adding the new singleton, allowing subsequent extensions to operate on a stable snapshot of the previous state.
The membership test longer not in next leverages Python’s list containment check, which, while linear in the size of next, prevents duplicate storage and thus curtails exponential growth of the result set. This trade-off balances simplicity with a practical reduction in memory usage for typical input sizes.
By updating todo only after processing all extensions for a given element, the code ensures that each element contributes to subsequences exactly once per iteration, eliminating redundant recombination of the same element with identical prefixes. This disciplined update pattern contributes to a more predictable execution flow.
ELI5 - Simplified Explanation
Imagine there is a big basket filled with numbered building blocks. The goal is to make smaller trains using those blocks. To build a train, the number on the next block must be the same size or bigger than the number before it.
This code starts by looking at the first block and putting it into a list of little trains. Then, it picks up the next block in the basket and looks at all the trains already sitting there. It tries to add this new block to the end of every existing train. If the new block is big enough to follow the one that came before it, the block gets attached to make a longer train.
Every time a new block is picked up, it becomes a new, short train all by itself, too. The code creates a new group of trains by keeping all the old ones and adding the new ones that were just made. It keeps doing this until every block in the basket has been picked up. Finally, it looks at all the trains created and keeps only the ones that have at least two blocks connected together.
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 | Go | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | charles-wangkai | Java | |||||||
| everthis | JS | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 646: Maximum Length of Pair Chain
Solved On The Same Day
- problem 566: Reshape the Matrix
- problem 594: Longest Harmonious Subsequence
- problem 324: Wiggle Sort II
- problem 386: Lexicographical Numbers
- problem 388: Longest Absolute File Path
- problem 390: Elimination Game
- problem 406: Queue Reconstruction by Height
- problem 410: Split Array Largest Sum
- problem 472: Concatenated Words
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