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' zero times.
  • Append the character '1' one times.

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
Building Good Strings: zero=1, one=1, low=2, high=3Start: "" (len=0)"0" (len=1)"1" (len=1)"00" (len=2)"01" (len=2)"10" (len=2)"11" (len=2)+1 zero+1 oneValid Range [2, 3]Length 2: 2 stringsLength 3: 2 stringsTotal: 2 good stringsEach step: add 'zero' zeros OR 'one' onesAnswer: 2
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
Asked in
Google 25 Meta 18 Amazon 15
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen