The Find All Possible Stable Binary Arrays II coding problem is a high-level counting challenge. You are asked to find the number of binary arrays (containing zero 0s and one 1s) such that no more than limit consecutive elements are the same. This is the optimized version of the problem, requiring an efficient solution for large inputs.
This "Hard" difficulty problem is used by IBM to evaluate a candidate's depth in Dynamic Programming and optimization. It tests the ability to transform a naive DP into an solution using prefix sums or sliding window techniques. It evaluation your understanding of combinatorial state transitions and how to handle subtraction of invalid states.
This problem uses Dynamic Programming with Prefix Sum Optimization.
dp[i][j][last_val] as the number of stable arrays with i zeros and j ones, ending in last_val (0 or 1).dp[i][j][0], you could have added a 0 to any stable array ending in 1, or added a sequence of zeros to a stable array ending in 1.dp[i][j][0] = sum(dp[i-k][j][1]) for .zero = 3, one = 3, limit = 2.
We want to count arrays like [0, 1, 0, 1, 0, 1] or [0, 0, 1, 1, 0, 1].
We exclude [0, 0, 0, 1, 1, 1] because it has 3 consecutive 0s and 3 consecutive 1s, exceeding the limit of 2.
The DP state builds these counts layer by layer, and the prefix sum allows us to quickly "subtract" the cases that became "unstable" (reached the limit+1 threshold).
(a - b) % mod can be negative. You must use (a - b + mod) % mod.When you see a DP transition that involves summing a range of previous values, always look for Prefix Sum Optimization. It is the standard way to reduce complexity by one dimension.