Problem Description
Given three positive integers zero, one, and limit, count how many binary arrays (arrays consisting of only 0’s and 1’s) of length (zero + one) exist that use exactly zero zeros and one ones and satisfy the following condition: every contiguous subarray longer than limit must contain both 0 and 1. In other words, the array is called “stable” if no block of consecutive identical elements (0 or 1) has length greater than limit. Return the count modulo 10^9+7.
Key Insights
- The subarray condition is equivalent to ensuring that no more than limit consecutive 0’s or 1’s occur in the array.
- The problem becomes counting the number of ways to interleave exactly zero zeros and one ones while restricting the maximum run length of each digit.
- A dynamic programming approach can be used where the state tracks the number of 0’s and 1’s used so far, the last placed element, and the length of its current run.
- Resetting the run counter occurs when switching the digit (from 0 to 1 or from 1 to 0).
Space and Time Complexity
Time Complexity: O(zero * one * limit * 2), since we consider each possible state defined by the count of zeros, ones, last digit, and current run length. Space Complexity: O(zero * one * limit * 2) due to the memoization or DP table storage.
Solution
We use a recursive dynamic programming approach with memoization. The recursion state is represented by:
- the number of zeros used so far,
- the number of ones used so far,
- the last digit appended (either 0 or 1, or undefined at the start),
- the current run length of that last digit.
For each state, we try to extend the array by appending a 0 or a 1 if possible under the limit constraint. When switching digits, the run length resets to 1. When continuing with the same digit, we only proceed if the current run length is less than limit. Our recursive function returns the count of valid completions from that state, and we add the results modulo 10^9+7. Iterative DP or bottom-up approaches are also possible. The trick is to notice that the problem is constrained by maximum consecutive repeats, and counting arrangements is a typical application of DP with state involving the current run length.