3130. Find All Possible Stable Binary Arrays II
Difficulty: Hard
Topics: Principal, Dynamic Programming, Prefix Sum, Biweekly Contest 129
You are given 3 positive integers zero, one, and limit.
A binary array1 arr is called stable if:
- The number of occurrences of 0 in
arris exactlyzero. - The number of occurrences of 1 in
arris exactlyone. - Each subarray2 of
arrwith a size greater thanlimitmust contain both 0 and 1.
Return the total number of stable binary arrays.
Since the answer may be very large, return it modulo 10⁹ + 7.
Example 1:
- Input: zero = 1, one = 1, limit = 2
- Output: 2
-
Explanation: The two possible stable binary arrays are
[1,0]and[0,1], as both arrays have a single 0 and a single 1, and no subarray has a length greater than 2.
Example 2:
- Input: zero = 1, one = 2, limit = 1
- Output: 1
-
Explanation:
- The only possible stable binary array is
[1,0,1]. - Note that the binary arrays
[1,1,0]and[0,1,1]have subarrays of length 2 with identical elements, hence, they are not stable.
- The only possible stable binary array is
Example 3:
- Input: zero = 3, one = 3, limit = 2
- Output: 14
-
Explanation: All the possible stable binary arrays are
[0,0,1,0,1,1],[0,0,1,1,0,1],[0,1,0,0,1,1],[0,1,0,1,0,1],[0,1,0,1,1,0],[0,1,1,0,0,1],[0,1,1,0,1,0],[1,0,0,1,0,1],[1,0,0,1,1,0],[1,0,1,0,0,1],[1,0,1,0,1,0],[1,0,1,1,0,0],[1,1,0,0,1,0], and[1,1,0,1,0,0].
Constraints:
1 <= zero, one, limit <= 1000
Hint:
- Let
dp[x][y][z = 0/1]be the number of stable arrays with exactlyxzeros,yones, and the last element isz. (0 or 1).dp[x][y][0] + dp[x][y][1]is the answer for given(x, y). - If we have already placed
x1 andy0, if we place a group ofk0, the number of ways isdp[x-k][y][1]. We can place a group with sizei, whereivaries from 1 tomin(limit, zero - x). Similarly, we can solve by placing a group of ones. - Speed up the calculation using prefix arrays to store the sum of
dpstates.
Solution:
We need to find the number of binary arrays of length zero+one, with exactly zero zeros and one ones, such that every subarray of length > limit contains both 0 and 1. This condition means that there is no subarray of length limit+1 or longer that is all zeros or all ones. In other words, the maximum consecutive run of zeros cannot exceed limit, and similarly for ones. Because if there were a run of zeros of length L > limit, then that subarray (the run itself) of length L > limit contains only zeros, violating condition. Conversely, if there is no run longer than limit, then any subarray longer than limit must contain both? Wait careful: The condition says: each subarray with size greater than limit must contain both 0 and 1. If the longest run of zeros is ≤ limit, could there be a subarray longer than limit that is all zeros? Not if the zeros are separated. But could there be a subarray longer than limit that consists of a mix of zeros and ones but still only zeros? No, it would have to be contiguous. So the condition is exactly that there is no contiguous block of identical bits of length > limit. That is necessary and sufficient? Let's think: Suppose there is a subarray of length > limit that contains both 0 and 1. That's fine. The only way a subarray of length > limit could violate is if it consists entirely of zeros or entirely of ones. So condition is equivalent to: no contiguous run of zeros longer than limit, and no contiguous run of ones longer than limit. Because any subarray that is all zeros must be contained within a maximal run of zeros. So if all runs are ≤ limit, then no subarray longer than limit can be all zeros or all ones. So yes, condition reduces to: maximum consecutive zeros ≤ limit and maximum consecutive ones ≤ limit. However, careful: Consider a subarray that starts and ends within a run but is longer than limit? That would require the run to be longer than limit. So condition is exactly that runs of zeros and ones are at most limit.
Approach:
-
State definition
-
dp0[i][j]– number of stable arrays withizeros,jones ending with0 -
dp1[i][j]– number withizeros,jones ending with1
-
-
Base cases
- A single run of zeros:
dp0[i][0] = 1if1 ≤ i ≤ limit(array consists only of zeros, but with at mostlimitconsecutive zeros) - A single run of ones:
dp1[0][j] = 1if1 ≤ j ≤ limit
- A single run of zeros:
-
Recurrence (naïve)
- To form
dp0[i][j], we take a sequence ending with1(havingi-kzeros,jones) and append a block ofkzeros (1 ≤ k ≤ min(limit, i)).dp0[i][j] = Σ_{k=1..min(limit,i)} dp1[i-k][j] - Similarly,
dp1[i][j] = Σ_{k=1..min(limit,j)} dp0[i][j-k]
- To form
-
Optimisation
- For
dp0, keep for eachja running sumsum1[j]ofdp1[i'][j]over the lastlimitvalues ofi'. Thendp0[i][j] = sum1[j] + base0(wherebase0handles the pure‑zero array case). - For
dp1, compute prefix sumspref0overdp0[i][*](for the currenti). Thendp1[i][j] = pref0[j-1] - pref0[max(0, j-limit)-1] + base1(using modular arithmetic). - Update the sliding window
sum1after computingdp1[i][*]by adding the new row and removing the row that falls out of the window.
- For
-
Answer
(dp0[zero][one] + dp1[zero][one]) mod 10⁹+7
Let's implement this solution in PHP: 3130. Find All Possible Stable Binary Arrays II
<?php
/**
* @param Integer $zero
* @param Integer $one
* @param Integer $limit
* @return Integer
*/
function numberOfStableArrays(int $zero, int $one, int $limit): int
{
...
...
...
/**
* go to ./solution.php
*/
}
// Test cases
echo numberOfStableArrays(1, 1, 2) . "\n"; // Output: 2
echo numberOfStableArrays(1, 2, 1) . "\n"; // Output: 1
echo numberOfStableArrays(3, 3, 2) . "\n"; // Output: 14
?>
Explanation:
-
Why two DP tables?
The last digit matters because the forbidden pattern (more than
limitidentical digits) is checked per run. By knowing the last digit we ensure we never exceed the allowed run length. -
Transitions via runs
- If the array ends with
0, the last run consists of consecutive zeros. The run length can be anykfrom 1 up tolimit. Before this run the array ended with1(or it is the very first run). Hence we sum over all possible previous counts of zeros (i-k) with the same number of ones (j) and last digit1. - Symmetrically for ending with
1.
- If the array ends with
-
Sliding‑window sum for
dp0- For a fixed
j,dp0[i][j]needs the sum ofdp1[i-k][j]fork=1..limit. This is exactly the sum of the lastlimitrows ofdp1(in theidimension) for thatj. -
sum1[j]is maintained as a sliding window: when we move fromi-1toi, we adddp1[i-1][j]and, ifi-1 ≥ limit, we subtractdp1[i-1-limit][j]. At the start of iterationi,sum1[j]already holds the required sum.
- For a fixed
-
Prefix sum for
dp1- For
dp1[i][j]we need the sum ofdp0[i][j-k]fork=1..limit. This is a range sum in thejdimension for the currenti. Precomputing prefix sumspref0for rowiallows O(1) range queries.
- For
-
Base cases
-
dp0[i][0]fori ≤ limitis 1 because the whole array is zeros and that run length is allowed. Similarlydp1[0][j]forj ≤ limit. These are incorporated asbase0andbase1to avoid double counting when the sliding‑window sum might be empty (e.g.,j=0fordp0).
-
-
Modulo handling
All additions and subtractions are taken modulo
10⁹+7to keep numbers within bounds.
Complexity
-
Time Complexity: O(zero · one) – two nested loops over
iandj, with constant‑time operations per state (sliding‑window updates and prefix‑sum lookups). -
Space Complexity: O(zero · one) – two DP tables of size
(zero+1) × (one+1). The sliding windowsum1and prefix arraypref0each use O(one) space.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:
Top comments (0)