Count Ways To Build Good Strings Problem
Description
LeetCode Problem 2466.
Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:
- Append the character
'0'zerotimes. - Append the character
'1'onetimes.
This can be performed any number of times.
A good string is a string constructed by the above process having a length between low and high (inclusive).
Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 10^9 + 7.
Example 1:
Input: low = 3, high = 3, zero = 1, one = 1
Output: 8
Explanation:
One possible valid good string is "011".
It can be constructed as follows: "" -> "0" -> "01" -> "011".
All binary strings from "000" to "111" are good strings in this example.
Example 2:
Input: low = 2, high = 3, zero = 1, one = 2
Output: 5
Explanation: The good strings are "00", "11", "000", "110", and "011".
Constraints:
1 <= low <= high <= 10^51 <= zero, one <= low
Solution
Approach: Dynamic Programming
Let f[i] be the number of different strings of length i that can be built. There is one empty string, so f[0] = 1. A string of length i ends with a block of zero zeros or a block of one ones, so
f[i] = f[i - zero] + f[i - one] (ignoring a term whose index is negative), taken modulo 109 + 7.
The answer is the sum of f[i] for low <= i <= high. Filling the table from small to large lengths avoids deep recursion.
Complexity: O(high) time and O(high) space.
class Solution:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
mod = 10**9 + 7
# f[i] = number of ways to get a string of length i
f = [0] * (high + 1)
f[0] = 1
for i in range(1, high + 1):
if i >= zero:
f[i] += f[i - zero]
if i >= one:
f[i] += f[i - one]
f[i] %= mod
return sum(f[low : high + 1]) % mod