Find All Possible Stable Binary Arrays I - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: zero = 1, one = 1, limit = 2
Output: 2
💡 Note: Two valid arrays: [0,1] and [1,0]. Both have exactly 1 zero and 1 one, and no subarray of length > 2 exists.
Example 2 — Larger Limit
$ Input: zero = 1, one = 2, limit = 1
Output: 1
💡 Note: Only [1,0,1] is valid. Arrays like [1,1,0] would have two consecutive 1s, violating limit=1.
Example 3 — Higher Counts
$ Input: zero = 3, one = 1, limit = 2
Output: 3
💡 Note: Valid arrays are [0,0,1,0], [0,1,0,0], and [1,0,0,0]. No more than 2 consecutive same digits allowed.

Constraints

  • 1 ≤ zero, one, limit ≤ 200

Visualization

Tap to expand
Stable Binary Arrays - Dynamic Programming INPUT Parameters: zero 1 one 1 limit 2 Constraints: - Exactly 1 zero in array - Exactly 1 one in array - Subarray size > 2 must have both 0 and 1 Valid Arrays: [0,1] [1,0] ALGORITHM STEPS 1 Define DP State dp[i][j][last] = count of arrays with i zeros, j ones 2 Track Consecutive Count consecutive same elements (must be <= limit) 3 Transitions Add 0 or 1 based on remaining count & limit 4 Sum Valid States Return dp[zero][one][*] modulo 10^9 + 7 DP Transitions: dp[1][0][0] = 1 (place 0) dp[0][1][1] = 1 (place 1) dp[1][1][0] = 1 --> [1,0] dp[1][1][1] = 1 --> [0,1] Total = 1 + 1 = 2 FINAL RESULT Stable Binary Arrays Found: 2 Valid Configurations: Array 1: [0, 1] 0 1 Array 2: [1, 0] 1 0 OK - Both are stable! No subarray > limit with only 0s or only 1s Key Insight: Use 3D Dynamic Programming: dp[zeros_used][ones_used][last_element] to track valid placements. The limit constraint requires tracking consecutive same elements. Transition only when adding an element doesn't create a run exceeding the limit. Time: O(zero * one * limit), Space: O(zero * one * 2). TutorialsPoint - Find All Possible Stable Binary Arrays I | Optimal DP Solution
Asked in
Google 25 Amazon 18 Facebook 15
12.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen