




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)
1function countGoodStrings(low, high, zero, one) {
2    const MOD = 1000000007;
3    const dp = Array(high + 1).fill(0);
4    dp[0] = 1;
5    for (let i = 1; i <= high; i++) {
6        if (i >= zero) dp[i] = (dp[i] + dp[i - zero]) % MOD;
7        if (i >= one) dp[i] = (dp[i] + dp[i - one]) % MOD;
8    }
9    let result = 0;
10    for (let i = low; i <= high; i++) {
11        result = (result + dp[i]) % MOD;
12    }
13    return result;
14}
15
16console.log(countGoodStrings(3, 3, 1, 1));This JavaScript solution follows the same approach as the others, utilizing an array dp to count good strings for each possible length. It accumulates the counts for length between low and high to obtain the 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.