Number of Good Binary Strings - Problem

You are given four integers minLength, maxLength, oneGroup and zeroGroup.

A binary string is good if it satisfies the following conditions:

  • The length of the string is in the range [minLength, maxLength].
  • The size of each block of consecutive 1's is a multiple of oneGroup.
  • The size of each block of consecutive 0's is a multiple of zeroGroup.

For example, in a binary string 00110111100, sizes of each block of consecutive ones are [2,4] and sizes of each block of consecutive zeros are [2,1,2].

Return the number of good binary strings. Since the answer may be too large, return it modulo 10⁹ + 7.

Note that 0 is considered a multiple of all numbers.

Input & Output

Example 1 — Basic Case
$ Input: minLength = 4, maxLength = 4, oneGroup = 4, zeroGroup = 3
Output: 2
💡 Note: Valid strings of length 4: '0000' (one block of 0s with size 4, but 4 % 3 ≠ 0, invalid) and '1111' (one block of 1s with size 4, 4 % 4 = 0, valid). Actually, let's recalculate: '0000' has block size 4, 4 % 3 ≠ 0 (invalid). '1111' has block size 4, 4 % 4 = 0 (valid). Other valid strings would need blocks of size 3 for 0s and size 4 for 1s.
Example 2 — Multiple Valid Strings
$ Input: minLength = 2, maxLength = 3, oneGroup = 2, zeroGroup = 1
Output: 8
💡 Note: For zeroGroup=1, any block of 0s is valid. For oneGroup=2, blocks of 1s must have even size. Valid strings include: '00', '11', '000', '011', '101', '110', etc.
Example 3 — No Valid Strings
$ Input: minLength = 1, maxLength = 1, oneGroup = 2, zeroGroup = 2
Output: 0
💡 Note: Length 1 strings are '0' or '1'. '0' has block size 1, but 1 % 2 ≠ 0. '1' has block size 1, but 1 % 2 ≠ 0. No valid strings exist.

Constraints

  • 1 ≤ minLength ≤ maxLength ≤ 105
  • 1 ≤ oneGroup, zeroGroup ≤ 105

Visualization

Tap to expand
Good Binary Strings: Block Constraint ValidationExample: oneGroup=2, zeroGroup=30 0 0 1 1 0 0 0 1 1Block: 000Block: 11Block: 000Size 3 ✓Size 2 ✓Size 3 ✓3%3=0, 2%2=0Constraints• 0-blocks: size % zeroGroup = 0• 1-blocks: size % oneGroup = 0• Length in [minLen, maxLen]✓ This string is GOODValid String Found!Count all such valid binary stringsReturn count modulo 10⁹ + 7
Understanding the Visualization
1
Input
Length range [minLength, maxLength] and group constraints
2
Process
Check consecutive block sizes against group requirements
3
Output
Count of valid binary strings
Key Takeaway
🎯 Key Insight: Use DP to track string building states rather than generating all possible strings
Asked in
Meta 15 Google 12 Amazon 8
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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