Count Ways To Build Good Strings - Problem
Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:
- Append the character '0'
zerotimes. - Append the character '1'
onetimes.
This can be performed any number of times.
A good string is a string constructed by the above process having a length between low and high (inclusive).
Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.
Input & Output
Example 1 — Basic Case
$
Input:
zero = 1, one = 1, low = 2, high = 3
›
Output:
2
💡 Note:
We can build strings of length 2 and 3: '00' (add 1 zero twice), '11' (add 1 one twice). Total = 2 good strings.
Example 2 — Different Step Sizes
$
Input:
zero = 2, one = 3, low = 6, high = 7
›
Output:
5
💡 Note:
Length 6: '000000' (3×zero), '000111' (zero+one), '111000' (one+zero). Length 7: '0000111' (zero+zero+one), '1110000' (one+zero+zero). Total = 5.
Example 3 — Single Valid Length
$
Input:
zero = 1, one = 2, low = 3, high = 3
›
Output:
2
💡 Note:
Only length 3 is valid: '000' (3×zero), '011' (zero+one). Total = 2 good strings.
Constraints
- 1 ≤ zero, one ≤ 50
- 1 ≤ low ≤ high ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
zero=1, one=1, low=2, high=3 (can add 1 zero or 1 one at each step)
2
Process
Build all possible string lengths from 0 to high
3
Output
Count strings with length in [low, high] range
Key Takeaway
🎯 Key Insight: Use DP to count ways to reach each length, then sum the counts for lengths in [low, high] range
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code