Python 0940.py
class Solution:
def distinctSubseqII(self, s: str) -> int:
# sequences ending with this character
last = [ 0 ] * 26
for c in s:
# append character to each already existing sequence
# and start a new sequence with c
last[ord(c) - 97] = sum(last) + 1 # ord("a") == 97
return sum(last) % 1_000_000_007
Difficulty
and has an acceptance rate of about 44% (100k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- String
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 distinct non-empty subsequences that can be formed from a given lowercase alphabetic string s. It follows a dynamic-programming style where the contribution of each character is aggregated into a fixed-size array that tracks subsequences ending with each letter. The final answer is obtained by summing the contributions and applying a modulus to keep the result within the required range.
Key Steps
Initialization of the tracking array
last = [0] * 26
A list of length 26 is created, one entry for each letter of the English alphabet. Each entry will hold the count of distinct subsequences that terminate with the corresponding character. The array is zero-initialized because no subsequences have been processed at the start.
Iteration over the input string
for c in s:
The algorithm walks through the characters of s in their original order. Processing characters sequentially guarantees that subsequences are built respecting the original ordering constraints.
Updating the count for the current character
last[ord(c) - 97] = sum(last) + 1
For the current character c, the index ord(c) - 97 maps it to the appropriate slot in last. The right-hand side computes the total number of distinct subsequences that have been seen so far (sum(last)) and adds one to represent the new subsequence consisting solely of c. By assigning this value to the slot for c, the algorithm effectively creates new subsequences by appending c to every existing subsequence and also counts the singleton subsequence [c]. The previous value stored for this character is overwritten because any subsequence ending with c that existed before is now subsumed by the newer, longer possibilities.
Final aggregation and modulus
return sum(last) % 1_000_000_007
After processing all characters, the sum of the array entries yields the total number of distinct non-empty subsequences. The result is reduced modulo 1_000_000_007, a large prime commonly used to avoid integer overflow in combinatorial counting problems.
Edge Cases Handled
When the input string is empty, the loop body never executes, leaving last filled with zeros. The final sum is therefore zero, correctly indicating that there are no non-empty subsequences.
If the string consists of a single repeated character, such as "aaa", each iteration overwrites the same slot in last. The computation sum(last) + 1 at each step accounts for the fact that adding another identical character does not create new distinct endings beyond the ones already represented, and the algorithm still counts each unique length-based subsequence exactly once.
For strings containing all 26 distinct letters, the array slots are each updated exactly once. The sum(last) term grows rapidly, but the modulus operation at the return stage ensures that the final value remains within the required numeric bounds.
Performance Optimizations
The algorithm uses a fixed-size array of length 26, which provides constant-time access to the count associated with any character. This eliminates the need for hash maps or dynamic structures that could introduce overhead.
The inner computation sum(last) aggregates the current state of the array in a single pass over 26 elements. Because the array size does not depend on the length of the input string, this operation runs in constant time relative to the alphabet size. Consequently, each iteration of the outer loop performs a bounded amount of work, leading to a linear relationship between the total runtime and the length of s.
By applying the modulus only once at the end, the implementation avoids repeated modular reductions during the iterative updates. This reduces the number of expensive arithmetic operations, especially when the intermediate sums become large.
Overall, the design leverages the limited alphabet to keep both memory usage and per-iteration work minimal, delivering an efficient solution for counting distinct subsequences.
ELI5 - Simplified Explanation
Imagine a row of twenty-six tiny treasure boxes, sitting neatly on a shelf, each waiting to hold different patterns made from the letters in a word. Every time a new letter appears in the word, the computer looks at all the patterns it has already built and adds a copy of those patterns plus the new letter itself into the box that matches that letter. Because some letters might appear more than once, the computer is very careful to clean out the old patterns in that box and replace them with the new count to make sure it does not count the same thing twice. By looking at all the treasures inside every box at the end, the total number of unique patterns is revealed.
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 | C | Go | Rust | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | Python |
Videos
Similar Problems
- problem 1987: Number of Unique Good Subsequences
- problem 2842: Count K-Subsequences of a String With Maximum Beauty
Solved On The Same Day
- problem 1894: Find the Student that Will Replace the Chalk
- problem 952: Largest Component Size by Common Factor
- problem 972: Equal Rational Numbers
- problem 1001: Grid Illumination
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