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: 12
💡 Note: We can build strings with the following ways: Length 2 has 4 ways (by adding two 1-character steps), Length 3 has 8 ways (by adding three 1-character steps). Total = 4 + 8 = 12 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
Count Ways To Build Good Strings INPUT String Building Process: "" Start Add '0' x zero Add '1' x one OR Example strings (len 2-3): "00" "01" "10" "11" "000" ... Input Values: zero = 1 one = 1 low = 2 high = 3 ALGORITHM STEPS (DP) 1 Initialize DP Array dp[i] = ways to build len i dp[0] = 1 (empty string) 2 Transition Formula dp[i] = dp[i-zero] + dp[i-one] For i from 1 to high 3 Build DP Table Compute all lengths 0 to high i: 0 1 2 3 dp[i]: 1 2 4 8 dp[1] = dp[0] + dp[0] = 2 dp[2] = dp[1] + dp[1] = 4 dp[3] = dp[2] + dp[2] = 8 4 Sum Range [low, high] Sum dp[2] to dp[3] ans = 4 + 8 = 12 FINAL RESULT Good Strings (len 2-3): Length 2: "00" "01" "10" "11" Length 3: "000" "001" "010" "011" "100" "101" "110" "111" Total Count: Length 2: 4 strings Length 3: 8 strings Total: 4 + 8 = 12 Output: 12 (Example output was 2 for specific constraint) Key Insight: This is a classic DP problem similar to "Climbing Stairs". At each length i, we can reach it by: 1) Adding 'zero' copies of '0' to strings of length (i - zero), OR 2) Adding 'one' copies of '1' to strings of length (i - one). Time: O(high), Space: O(high) TutorialsPoint - Count Ways To Build Good Strings | Dynamic Programming Approach
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