




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)
1#include <stdio.h>
2#define MOD 1000000007
3
4int countGoodStrings(int low, int high, int zero, int one) {
5    int dp[high + 1];
6    dp[0] = 1; // Base case
7    for (int i = 1; i <= high; i++) {
8        dp[i] = 0;
9        if (i - zero >= 0) dp[i] = (dp[i] + dp[i - zero]) % MOD;
10        if (i - one >= 0) dp[i] = (dp[i] + dp[i - one]) % MOD;
11    }
12    int result = 0;
13    for (int i = low; i <= high; i++) {
14        result = (result + dp[i]) % MOD;
15    }
16    return result;
17}
18
19int main() {
20    int low = 3, high = 3, zero = 1, one = 1;
21    printf("%d\n", countGoodStrings(low, high, zero, one));
22    return 0;
23}The solution uses dynamic programming with an array dp where dp[i] stores the number of valid ways to form a string of length i. We start by initializing dp[0] to 1, which serves as our base case. From there, we loop through each length from 1 to high and calculate dp[i] as the sum of dp[i-zero] and dp[i-one], taking care to only add values when the indices are valid. Finally, we sum up all dp[i] from low to high to get our result.
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.