Number of Unique Good Subsequences Problem
Description
LeetCode Problem 1987.
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").
Find the number of unique good subsequences of binary.
- For example, if
binary = "001", then all the good subsequences are["0", "0", "1"], so the unique good subsequences are"0"and"1". Note that subsequences"00","01", and"001"are not good because they have leading zeros.
Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: binary = "001"
Output: 2
Explanation: The good subsequences of binary are ["0", "0", "1"].
The unique good subsequences are "0" and "1".
Example 2:
Input: binary = "11"
Output: 2
Explanation: The good subsequences of binary are ["1", "1", "11"].
The unique good subsequences are "1" and "11".
Example 3:
Input: binary = "101"
Output: 5
Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"].
The unique good subsequences are "0", "1", "10", "11", and "101".
Constraints:
1 <= binary.length <= 10^5binaryconsists of only'0's and'1's.
Solution
Approach: Dynamic Programming
Let f be the number of distinct good subsequences that end with 1 (they start with 1), and g the number of distinct ones that start with 1 and end with 0. Scan the string from left to right:
- on a
0, every subsequence counted so far can be extended by it, and extending the ones ending in1or0gives all the new ones ending in0:g = g + f; - on a
1, extend every counted subsequence, or start a new one with just this1:f = f + g + 1.
Taking the new value as the total for that ending counts each distinct subsequence once. All values are taken modulo 10^9 + 7. The only good subsequence starting with 0 is "0" itself, so add 1 to f + g if the string contains a 0.
Complexity: time O(n), space O(1).
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 ans