Count Ways To Build Good Strings - Problem
You're a string architect tasked with building strings using a unique construction process. You start with an empty string and can repeatedly perform one of two operations:
- Add
zeroconsecutive '0' characters - Add
oneconsecutive '1' characters
For example, if zero = 2 and one = 3, you could build strings like:
- "00" (one operation: add 2 zeros)
- "111" (one operation: add 3 ones)
- "00111" (two operations: add 2 zeros, then 3 ones)
- "11100" (two operations: add 3 ones, then 2 zeros)
A good string is one whose length falls between low and high (inclusive). Your goal is to count how many different good strings can be constructed using this process.
Since the answer can be extremely large, return it modulo 109 + 7.
Input & Output
example_1.py โ Basic Case
$
Input:
low = 3, high = 3, zero = 1, one = 1
โบ
Output:
8
๐ก Note:
We need strings of exactly length 3. With zero=1 and one=1, we can add one '0' or one '1' at each step. All possible strings: "000", "001", "010", "011", "100", "101", "110", "111". Total: 8 strings.
example_2.py โ Range Case
$
Input:
low = 2, high = 3, zero = 1, one = 2
โบ
Output:
5
๐ก Note:
With zero=1 (add one '0') and one=2 (add two '1's), we can build: Length 2: "00", "11" (2 strings). Length 3: "000", "011", "110" (3 strings). Total: 2 + 3 = 5 strings.
example_3.py โ Large Numbers
$
Input:
low = 1, high = 100000, zero = 1, one = 1
โบ
Output:
215447031
๐ก Note:
This is essentially counting binary strings of length 1 to 100000. For length n, there are 2^n strings. We sum 2^1 + 2^2 + ... + 2^100000 and take modulo 10^9+7, which equals 215447031.
Constraints
- 1 โค low โค high โค 105
- 1 โค zero, one โค high
- Answer fits in 32-bit integer after taking modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Start with empty foundation
Begin with length 0 - there's exactly 1 way to have nothing
2
Add blocks incrementally
For each length i, count ways by adding block of size 'zero' to length (i-zero) or block of size 'one' to length (i-one)
3
Build up to target length
Continue this process until we've calculated ways for all lengths up to 'high'
4
Sum the valid range
Add up all the ways for lengths between 'low' and 'high' inclusive
Key Takeaway
๐ฏ Key Insight: This problem transforms from exponential recursion to linear DP by recognizing that each length can be built by extending shorter valid lengths. The magic happens when we realize dp[i] depends only on dp[i-zero] and dp[i-one]!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code