




Sponsored
Sponsored
We can solve this problem using a dynamic programming approach. The idea is to maintain a dp array where dp[i] represents the number of good strings of exact length i. Start with an empty string and attempt to form strings by appending '0's and '1's zero and one times respectively. For each length from low to high, we incrementally calculate the number of ways to achieve that length from smaller lengths and store them in dp[i].
Time Complexity: O(high)
Space Complexity: O(high)
1def countGoodStrings(low, high, zero, one):
2    MOD = 1000000007
3    dp = [0] * (high + 1)
4    dp[0] = 1
5    for i in range(1, high + 1):
6        if i >= zero:
7            dp[i] = (dp[i] + dp[i - zero]) % MOD
8        if i >= one:
9            dp[i] = (dp[i] + dp[i - one]) % MOD
10    return sum(dp[low:high + 1]) % MOD
11
12print(countGoodStrings(3, 3, 1, 1))This Python solution implements the DP approach where we maintain a list dp to store the number of valid strings of each possible length. Using a loop, we calculate possible strings by adding previous results. Finally, we sum the relevant part of the list to get the total answer.
In this approach, we explore every possible string configuration using backtracking to find strings whose lengths fall between low and high. We use recursion to build strings by appending zero or one '0's and '1's, tracking lengths and adding valid ones to a result set. Although not as efficient as the DP method due to exponential complexity, it serves as an insightful means to intuitively grasp the construction of such strings.
Time Complexity: O(2^n) where n is high / min(zero, one)
Space Complexity: O(n) because of the recursion stack
1def countGoodStrings(low, high, zero, one):
2    MOD = 
The backtracking solution in Python employs a recursive function to consider adding either zero or one characters to a string. It tracks the length of each created string and counts those which are valid. Once a length exceeds high, recursion stops further exploration from that branch.