Count Ways To Build Good Strings (LeetCode 2466): Solution and Explanation

Medium
Dynamic Programming

Count the strings you can build by repeatedly appending a block of zeros or a block of ones, keeping only those whose length lands between low and high.

Intuition

The exact characters of a built string never matter for how it can grow. Only its length does, because the next step always appends a fixed block of zeros or a fixed block of ones.

Look at the last block of any built string of length i. It is either zero zeros or one ones. Remove it and you are left with a built string of length i - zero or i - one. Different choices of the last block give different strings, so the counts simply add.

That gives the recurrence dp[i] = dp[i - zero] + dp[i - one], which is climbing stairs with step sizes zero and one. The empty string is the single way to reach length 0.

The answer is the sum of dp[i] over the good lengths from low to high, taken modulo 1e9+7.

Approach: Bottom-up DP over length

  1. Create dp of size high + 1 filled with 0 and set dp[0] = 1.
  2. For each length i from 1 to high, set dp[i] = dp[i - zero] when i >= zero.
  3. Then add dp[i - one] when i >= one, applying the modulo.
  4. If i >= low, add dp[i] to the answer, again modulo 10^9 + 7.
  5. Return the answer.

Step-by-step example

low = 3, high = 3, zero = 1, one = 1
  1. dp[0] = 1: only the empty string.
  2. dp[1] = dp[0] + dp[0] = 2: "0" and "1".
  3. dp[2] = dp[1] + dp[1] = 4: each length 1 string gets a '0' or a '1'.
  4. dp[3] = dp[2] + dp[2] = 8. Length 3 is the only good length, so the answer is 8.

Code: Python, Java, C++

1class Solution:
2    def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
3        MOD = 10**9 + 7
4        dp = [0] * (high + 1)
5        dp[0] = 1
6        ans = 0
7        for i in range(1, high + 1):
8            if i >= zero:
9                dp[i] = dp[i - zero]
10            if i >= one:
11                dp[i] = (dp[i] + dp[i - one]) % MOD
12            if i >= low:
13                ans = (ans + dp[i]) % MOD
14        return ans
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(high)

Each length from 1 to high is filled once with two constant-time lookups.

Space

O(high)

The dp array has one entry per length. A circular buffer of size max(zero, one) + 1 could reduce this, but the array is simpler.

Other approaches

Top-down memoized recursion (time O(high), space O(high))

Count the ways to extend a string of length L: 1 if L is good, plus the counts after appending each block, stopping above high. Same complexity, but deep recursion on high = 10^5 risks a stack overflow.

Enumerate every string (time O(2^(high / min(zero, one))), space O(high))

Generate all block sequences with backtracking and count those of good length. Correct for tiny inputs, but the number of strings grows exponentially with high.

Common mistakes

  • Forgetting the modulo after the addition, which overflows 32-bit integers in Java and C++ once the counts grow.
  • Indexing dp[i - zero] or dp[i - one] when i is smaller than the block, which reads a negative index (or wraps in Python).
  • Counting dp[i] for lengths below low. Short strings still feed longer ones, but they are not good themselves.
  • Treating zero and one as characters or booleans. They are block lengths, and they can be equal, in which case both terms are added.

Frequently asked questions

Why is this the same as climbing stairs?

Climbing stairs counts ordered sequences of 1-steps and 2-steps that reach a height. Here you count ordered sequences of zero-blocks and one-blocks that reach a length. Replace the step sizes 1 and 2 with zero and one and the recurrence is identical.

What if zero equals one?

The two blocks have the same length but different characters, so they still make different strings. dp[i] becomes 2 * dp[i - zero], and the code handles it without a special case.

Can two different block sequences produce the same string?

No. Reading the string from the left, each block starts with a '0' or a '1', which tells you which block it is and how long it is. So the block sequence is fixed by the string, and counting sequences counts strings.

What is the time complexity?

O(high) time and O(high) space, since each length is computed once from two earlier entries.