Find All Possible Stable Binary Arrays II Problem
#3130
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3130.
You are given 3 positive integers num_zeros, num_ones, and limit.
A binary array arr is called stable if:
- The number of occurrences of 0 in
arris exactlynum_zeros. - The number of occurrences of 1 in
arris exactlynum_ones. - Each subarray of
arrwith a size greater thanlimitmust contain at least one occurrence of both 0 and 1.
Return an integer denoting the total number of stable binary arrays.
Since the answer may be very large, return it modulo 10^9 + 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].
Example 2:
Input: zero = 1, one = 2, limit = 1
Output: 1
Explanation:
The only possible stable binary array is [1,0,1].
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
Solution
Approach: Memoization Search
Let dfs(i, j, k) be the number of stable arrays that can still be built when i zeros and j ones remain and the next element to place is k. The answer is dfs(zero, one, 0) + dfs(zero, one, 1).
- If
i < 0orj < 0, there is nothing to count: return0. - If
i = 0, only ones remain, so the result is1whenk = 1andj <= limit, else0. - If
j = 0, the symmetric rule applies:1whenk = 0andi <= limit, else0. - If
k = 0, the previous element is either0or1, givingdfs(i - 1, j, 0) + dfs(i - 1, j, 1). Placing a0can create a run oflimit + 1zeros, which happens exactly when the(limit + 1)-th element from the end is a1; those arrays are subtracted:dfs(i - limit - 1, j, 1). - If
k = 1, the same argument with the roles swapped givesdfs(i, j - 1, 0) + dfs(i, j - 1, 1) - dfs(i, j - limit - 1, 0).
Results are cached so each state is computed once, and everything is taken modulo 10^9 + 7.
Complexity: time O(zero * one), space O(zero * one).
from functools import lru_cache
class Solution:
def numberOfStableArrays(self, zero: int, one: int, limit: int) -> int:
mod = 10**9 + 7
@lru_cache(None)
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))
) % mod
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
ans = (dfs(zero, one, 0) + dfs(zero, one, 1)) % mod
dfs.cache_clear()
return ans