Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2466. Count Ways To Build Good Strings

Dynamic Programming

Explanation

To solve this problem, we can use dynamic programming to build a solution iteratively. We create a 3D DP array where dp[i][j][k] represents the number of ways to build a good string of length i using j zeros and k ones. We iterate through the possible values for i, j, and k to calculate the number of ways to build good strings that meet the constraints.

At each step, we consider the two choices we have: appending a '0' or a '1'. We update the DP array based on these choices and the constraints provided. Finally, we sum up all valid combinations to get the total number of ways to build good strings within the specified length range.

  • Time complexity: O(N * low * one) where N is the difference between high and low.
  • Space complexity: O(N * low * one).
class Solution {
    public int countGoodStrings(int low, int high, int zero, int one) {
        int MOD = 1000000007;
        int n = high - low + 1;
        int[][][] dp = new int[n + 1][zero + 1][one + 1];
        
        dp[0][0][0] = 1;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= zero; j++) {
                for (int k = 0; k <= one; k++) {
                    for (int z = 0; z <= j; z++) {
                        for (int o = 0; o <= k; o++) {
                            if (z <= j && o <= k && z + o > 0) {
                                dp[i][j][k] = (dp[i][j][k] + dp[i - 1][j - z][k - o]) % MOD;
                            }
                        }
                    }
                }
            }
        }
        
        int ans = 0;
        for (int j = 0; j <= zero; j++) {
            for (int k = 0; k <= one; k++) {
                ans = (ans + dp[n][j][k]) % MOD;
            }
        }
        
        return ans;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.