Ways to Split Array Into Good Subarrays - Problem

You are given a binary array nums.

A subarray of an array is good if it contains exactly one element with the value 1.

Return an integer denoting the number of ways to split the array nums into good subarrays. As the number may be too large, return it modulo 109 + 7.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1,0,0,1,0,1]
Output: 6
💡 Note: There are 6 ways to split: [0,1]|[0,0,1]|[0,1], [0,1]|[0,0,1,0]|[1], [0,1,0]|[0,1]|[0,1], [0,1,0]|[0,1,0]|[1], [0,1,0,0]|[1]|[0,1], [0,1,0,0]|[1,0]|[1]
Example 2 — Single 1
$ Input: nums = [0,1,0]
Output: 1
💡 Note: Only one way to split: [0,1,0] as a single subarray containing exactly one 1
Example 3 — No Valid Split
$ Input: nums = [1,1,0,1]
Output: 0
💡 Note: Cannot create subarrays with exactly one 1 each - any split will have some subarray with 0 or multiple 1s

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Visualization

Tap to expand
Ways to Split Array Into Good Subarrays INPUT Binary Array nums: 0 i=0 1 i=1 0 i=2 0 i=3 1 i=4 0 i=5 1 i=6 Positions of 1s: [1, 4, 6] Gaps between 1s: Gap 1 4-1 = 3 Gap 2 6-4 = 2 Split points = gaps between consecutive 1s ALGORITHM STEPS 1 Find all 1s positions Iterate and record indices 2 Calculate gaps Gap = pos[i+1] - pos[i] 3 Multiply all gaps Result = gap1 * gap2 * ... 4 Return modulo 10^9+7 Handle large numbers Calculation: Positions: [1, 4, 6] Gap1: 4 - 1 = 3 Gap2: 6 - 4 = 2 Result: 3 * 2 = 6 FINAL RESULT 6 Valid Splits: [0,1] | [0,0,1] | [0,1] [0,1] | [0,0,1,0] | [1] [0,1,0] | [0,1] | [0,1] [0,1,0] | [0,1,0] | [1] [0,1,0,0] | [1] | [0,1] [0,1,0,0] | [1,0] | [1] Output: 6 OK - Valid Result Key Insight: Each "good" subarray must contain exactly ONE '1'. Between two consecutive 1s, we can place the split at any position in the gap. If gap has 'k' zeros, there are 'k' split points. Total ways = product of all gaps. Formula: ways = (pos[1]-pos[0]) * (pos[2]-pos[1]) * ... * (pos[n-1]-pos[n-2]) mod (10^9+7) TutorialsPoint - Ways to Split Array Into Good Subarrays | Optimal Solution Time Complexity: O(n) | Space Complexity: O(1)
Asked in
Meta 15 Google 12 Microsoft 8
23.5K Views
Medium Frequency
~15 min Avg. Time
892 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