Magicsheet logo

Find All Possible Stable Binary Arrays II

Hard
35%
Updated 6/1/2025

Asked by 1 Company

Find All Possible Stable Binary Arrays II

What is this problem about?

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.

Why is this asked in interviews?

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 O(Nimeslimit)O(N imes limit) DP into an O(N)O(N) solution using prefix sums or sliding window techniques. It evaluation your understanding of combinatorial state transitions and how to handle subtraction of invalid states.

Algorithmic pattern used

This problem uses Dynamic Programming with Prefix Sum Optimization.

  1. Define dp[i][j][last_val] as the number of stable arrays with i zeros and j ones, ending in last_val (0 or 1).
  2. For 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.
  3. Naive transition: dp[i][j][0] = sum(dp[i-k][j][1]) for 1klimit1 \le k \le limit.
  4. Optimization: Instead of summing kk terms, maintain a running prefix sum of the other DP state. The sum can then be calculated in O(1)O(1) by subtracting an old prefix sum from the current one.

Example explanation

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).

Common mistakes candidates make

  • Integer overflow: Forgetting to apply the modulo at every addition and subtraction step.
  • Handling negative results: In some languages, (a - b) % mod can be negative. You must use (a - b + mod) % mod.
  • Complexity: Attempting to solve it in O(Nimeslimit)O(N imes limit), which is too slow for the "II" version of the problem where NN and limitlimit are large.

Interview preparation tip

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.

Similar Questions