Number of Good Binary Strings — LeetCode 2533 Python Solution

MediumLeetCode PremiumDynamic Programming
Problem
#2533
Reading time
3 min

The problem

You are given four integers minLength, maxLength, oneGroup and zeroGroup. A binary string is good if it satisfies the following conditions: The length of the string is in the range [minLength, maxLength].

Example

Input
minLength = 2, maxLength = 3, oneGroup = 1, zeroGroup = 2
Output
5
Explanation
There are 5 good binary strings in this example: "00", "11", "001", "100", and "111".

Python solution

Python
class Solution:
    def goodBinaryStrings(
        self, minLength: int, maxLength: int, oneGroup: int, zeroGroup: int
    ) -> int:
        mod = 10**9 + 7
        f = [1] + [0] * maxLength
        for i in range(1, len(f)):
            if i - oneGroup >= 0:
                f[i] += f[i - oneGroup]
            if i - zeroGroup >= 0:
                f[i] += f[i - zeroGroup]
            f[i] %= mod
        return sum(f[minLength:]) % mod

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n=maxLength auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2533. Number of Good Binary Strings 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 2533. Number of Good Binary Strings?
LeetCode 2533. Number of Good Binary Strings is rated Medium on LeetCode.
What is the time complexity of LeetCode 2533. Number of Good Binary Strings?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2533. Number of Good Binary Strings?
The Python solution on this page uses O(n), where n=maxLength auxiliary space.
What topics does LeetCode 2533. Number of Good Binary Strings cover?
LeetCode 2533. Number of Good Binary Strings is tagged Dynamic Programming on LeetCode.
Is LeetCode 2533. Number of Good Binary Strings a premium problem?
Yes. LeetCode 2533. Number of Good Binary Strings is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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