Number of Unique Good Subsequences — LeetCode 1987 Python Solution

HardStringDynamic Programming
Problem
#1987
Reading time
2 min

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

Python
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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview