We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Ways To Build Good Strings

Number: 2562

Difficulty: Medium

Paid? No

Companies: Amazon, Citadel, Google, Oracle


Problem Description

Given integers low, high, zero, and one, we need to count the number of different binary strings that can be built by starting with an empty string and repeatedly appending either a block of '0's of length zero or a block of '1's of length one. The resulting string must have a length between low and high (inclusive). Return the total count modulo 10^9 + 7.


Key Insights

  • The solution uses dynamic programming to count ways to form strings of various lengths.
  • Define dp[i] as the number of ways to form a string of length i.
  • Start with dp[0] = 1 (the empty string).
  • For each valid length i, update dp[i + zero] and dp[i + one] if they do not exceed high.
  • Sum up the results from dp[low] to dp[high] to get the final answer.
  • Use modulo arithmetic (10^9 + 7) at every update to keep the numbers manageable.

Space and Time Complexity

Time Complexity: O(high)
Space Complexity: O(high)


Solution

We use a bottom-up dynamic programming approach. A dp array of size high + 1 is initialized with dp[0] set to 1. For each index i from 0 to high, if there is any way to form a string of length i, then:

  • Add dp[i] to dp[i + zero] (if i + zero ≤ high).
  • Add dp[i] to dp[i + one] (if i + one ≤ high). After processing all indices, we sum the values in dp from index low to high and return the result mod 10^9 + 7.

Code Solutions

MOD = 10**9 + 7

def countGoodStrings(low, high, zero, one):
    # dp[i] represents the number of ways to form a string of length i.
    dp = [0] * (high + 1)
    dp[0] = 1  # Base case: one way to form the empty string
    
    for i in range(high + 1):
        if dp[i]:
            # Append a block of '0's
            if i + zero <= high:
                dp[i + zero] = (dp[i + zero] + dp[i]) % MOD
            # Append a block of '1's
            if i + one <= high:
                dp[i + one] = (dp[i + one] + dp[i]) % MOD
                
    # Sum all ways for valid string lengths
    return sum(dp[low:high+1]) % MOD

# Example usage:
print(countGoodStrings(3, 3, 1, 1))  # Output: 8
← Back to All Questions