You are given 3 positive integers zero, one, and limit.
A binary arrayarr is called stable if:
The number of occurrences of 0 in arr is exactly zero.
The number of occurrences of 1 in arr is exactlyone.
Each subarray of arr with a size greater than limit must contain both 0 and 1.
Return the total number of stable binary arrays.
Since the answer may be very large, return it modulo109 + 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.
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].
Problem summary: You are given 3 positive integers zero, one, and limit. A binary array arr is called stable if: The number of occurrences of 0 in arr is exactly zero. The number of occurrences of 1 in arr is exactly one. Each subarray of arr with a size greater than limit must contain both 0 and 1. Return the total number of stable binary arrays. Since the answer may be very large, return it modulo 109 + 7.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
1
1
2
Example 2
1
2
1
Example 3
3
3
2
Related Problems
Contiguous Array (contiguous-array)
Binary Subarrays With Sum (binary-subarrays-with-sum)
Step 02
Core Insight
What unlocks the optimal approach
Let <code>dp[a][b][c = 0/1][d]</code> be the number of stable arrays with exactly <code>a</code> 0s, <code>b</code> 1s and consecutive <code>d</code> value of <code>c</code>’s at the end.
Try each case by appending a 0/1 at last to get the inductions.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3129: Find All Possible Stable Binary Arrays I
class Solution {
private final int mod = (int) 1e9 + 7;
private Long[][][] f;
private int limit;
public int numberOfStableArrays(int zero, int one, int limit) {
f = new Long[zero + 1][one + 1][2];
this.limit = limit;
return (int) ((dfs(zero, one, 0) + dfs(zero, one, 1)) % mod);
}
private long dfs(int i, int j, int k) {
if (i < 0 || j < 0) {
return 0;
}
if (i == 0) {
return k == 1 && j <= limit ? 1 : 0;
}
if (j == 0) {
return k == 0 && i <= limit ? 1 : 0;
}
if (f[i][j][k] != null) {
return f[i][j][k];
}
if (k == 0) {
f[i][j][k]
= (dfs(i - 1, j, 0) + dfs(i - 1, j, 1) - dfs(i - limit - 1, j, 1) + mod) % mod;
} else {
f[i][j][k]
= (dfs(i, j - 1, 0) + dfs(i, j - 1, 1) - dfs(i, j - limit - 1, 0) + mod) % mod;
}
return f[i][j][k];
}
}
// Accepted solution for LeetCode #3129: Find All Possible Stable Binary Arrays I
func numberOfStableArrays(zero int, one int, limit int) int {
const mod int = 1e9 + 7
f := make([][][2]int, zero+1)
for i := range f {
f[i] = make([][2]int, one+1)
for j := range f[i] {
f[i][j] = [2]int{-1, -1}
}
}
var dfs func(i, j, k int) int
dfs = func(i, j, k int) int {
if i < 0 || j < 0 {
return 0
}
if i == 0 {
if k == 1 && j <= limit {
return 1
}
return 0
}
if j == 0 {
if k == 0 && i <= limit {
return 1
}
return 0
}
res := &f[i][j][k]
if *res != -1 {
return *res
}
if k == 0 {
*res = (dfs(i-1, j, 0) + dfs(i-1, j, 1) - dfs(i-limit-1, j, 1) + mod) % mod
} else {
*res = (dfs(i, j-1, 0) + dfs(i, j-1, 1) - dfs(i, j-limit-1, 0) + mod) % mod
}
return *res
}
return (dfs(zero, one, 0) + dfs(zero, one, 1)) % mod
}
# Accepted solution for LeetCode #3129: Find All Possible Stable Binary Arrays I
class Solution:
def numberOfStableArrays(self, zero: int, one: int, limit: int) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if i == 0:
return int(k == 1 and j <= limit)
if j == 0:
return int(k == 0 and i <= limit)
if k == 0:
return (
dfs(i - 1, j, 0)
+ dfs(i - 1, j, 1)
- (0 if i - limit - 1 < 0 else dfs(i - limit - 1, j, 1))
)
return (
dfs(i, j - 1, 0)
+ dfs(i, j - 1, 1)
- (0 if j - limit - 1 < 0 else dfs(i, j - limit - 1, 0))
)
mod = 10**9 + 7
ans = (dfs(zero, one, 0) + dfs(zero, one, 1)) % mod
dfs.cache_clear()
return ans
// Accepted solution for LeetCode #3129: Find All Possible Stable Binary Arrays I
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3129: Find All Possible Stable Binary Arrays I
// class Solution {
// private final int mod = (int) 1e9 + 7;
// private Long[][][] f;
// private int limit;
//
// public int numberOfStableArrays(int zero, int one, int limit) {
// f = new Long[zero + 1][one + 1][2];
// this.limit = limit;
// return (int) ((dfs(zero, one, 0) + dfs(zero, one, 1)) % mod);
// }
//
// private long dfs(int i, int j, int k) {
// if (i < 0 || j < 0) {
// return 0;
// }
// if (i == 0) {
// return k == 1 && j <= limit ? 1 : 0;
// }
// if (j == 0) {
// return k == 0 && i <= limit ? 1 : 0;
// }
// if (f[i][j][k] != null) {
// return f[i][j][k];
// }
// if (k == 0) {
// f[i][j][k]
// = (dfs(i - 1, j, 0) + dfs(i - 1, j, 1) - dfs(i - limit - 1, j, 1) + mod) % mod;
// } else {
// f[i][j][k]
// = (dfs(i, j - 1, 0) + dfs(i, j - 1, 1) - dfs(i, j - limit - 1, 0) + mod) % mod;
// }
// return f[i][j][k];
// }
// }
// Accepted solution for LeetCode #3129: Find All Possible Stable Binary Arrays I
function numberOfStableArrays(zero: number, one: number, limit: number): number {
const mod = 1e9 + 7;
const f: number[][][] = Array.from({ length: zero + 1 }, () =>
Array.from({ length: one + 1 }, () => [-1, -1]),
);
const dfs = (i: number, j: number, k: number): number => {
if (i < 0 || j < 0) {
return 0;
}
if (i === 0) {
return k === 1 && j <= limit ? 1 : 0;
}
if (j === 0) {
return k === 0 && i <= limit ? 1 : 0;
}
let res = f[i][j][k];
if (res !== -1) {
return res;
}
if (k === 0) {
res = (dfs(i - 1, j, 0) + dfs(i - 1, j, 1) - dfs(i - limit - 1, j, 1) + mod) % mod;
} else {
res = (dfs(i, j - 1, 0) + dfs(i, j - 1, 1) - dfs(i, j - limit - 1, 0) + mod) % mod;
}
return (f[i][j][k] = res);
};
return (dfs(zero, one, 0) + dfs(zero, one, 1)) % mod;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(zero × one)
Space
O(zero × one)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.