Number of Unique Good Subsequences — LeetCode 1987 Python Solution
- Problem
- #1987
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").
Example
- Input
- binary = "001"
- Output
- 2
- Explanation
- The good subsequences of binary are ["0", "0", "1"].
Python solution
class Solution:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
f = g = 0
ans = 0
mod = 10**9 + 7
for c in binary:
if c == "0":
g = (g + f) % mod
ans = 1
else:
f = (f + g + 1) % mod
ans = (ans + f + g) % mod
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(1) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1987. Number of Unique Good Subsequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1987. Number of Unique Good Subsequences?
- LeetCode 1987. Number of Unique Good Subsequences is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1987. Number of Unique Good Subsequences?
- The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 1987. Number of Unique Good Subsequences?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1987. Number of Unique Good Subsequences cover?
- LeetCode 1987. Number of Unique Good Subsequences is tagged String and Dynamic Programming on LeetCode.