Find All Possible Stable Binary Arrays II - Problem
You are tasked with constructing stable binary arrays - a fascinating combinatorial problem that tests your dynamic programming skills!
Given three positive integers zero, one, and limit, you need to count how many different binary arrays can be formed that satisfy these conditions:
- The array contains exactly
zerooccurrences of 0 - The array contains exactly
oneoccurrences of 1 - No subarray of length greater than
limitcan contain only 0s or only 1s (this ensures stability)
The third condition is the key constraint - it prevents long streaks of consecutive identical digits, making the array "stable" by ensuring diversity in longer subsequences.
Return the total number of such stable binary arrays. Since this number can be astronomically large, return it modulo 109 + 7.
Example: If zero=1, one=1, limit=2, valid arrays are [0,1] and [1,0], so the answer is 2.
Input & Output
example_1.py — Basic Case
$
Input:
zero = 1, one = 1, limit = 2
›
Output:
2
💡 Note:
With 1 zero and 1 one, we can form arrays [0,1] and [1,0]. Both are stable since no subarray longer than limit=2 contains only one type of digit. Total: 2 valid arrays.
example_2.py — Longer Array
$
Input:
zero = 1, one = 2, limit = 1
›
Output:
1
💡 Note:
With limit=1, no two consecutive digits can be the same. The only valid arrangement is [0,1,0] - we must alternate. Arrays like [1,1,0] are invalid because '11' exceeds the limit.
example_3.py — Higher Limit
$
Input:
zero = 3, one = 3, limit = 2
›
Output:
14
💡 Note:
With limit=2, we can have at most 2 consecutive 0s or 1s. This allows many more arrangements than alternating, but still prevents long streaks like '000' or '111'.
Constraints
- 1 ≤ zero, one ≤ 200
- 1 ≤ limit ≤ 200
- Answer must be returned modulo 109 + 7
- Array length will be zero + one
Visualization
Tap to expand
Understanding the Visualization
1
Start Empty
Begin with an empty array and full quota of 0s and 1s
2
Make Valid Choices
At each position, choose 0 or 1 based on remaining quota and consecutive limit
3
Track Consecutive Count
Monitor how many consecutive identical digits we've placed
4
Use Memoization
Cache results for identical states to avoid redundant computation
Key Takeaway
🎯 Key Insight: Dynamic programming with state memoization transforms an exponential problem into a polynomial one by tracking only the essential information needed for future decisions.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code