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: [0,1,0,0,1,0,1] → 6 ways01001011st2nd3rdGap = 3 positionsGap = 2 positionsEach subarray must contain exactly one 1Total ways = 3 × 2 = 6Split positions can be placed anywhere in the gaps between 1sExamples: [0,1]|[0,0,1]|[0,1] or [0,1,0]|[0,1]|[0,1]
Understanding the Visualization
1
Input
Binary array [0,1,0,0,1,0,1]
2
Process
Find gaps between consecutive 1s
3
Output
Multiply gaps: 3 × 2 = 6 ways
Key Takeaway
🎯 Key Insight: The number of ways equals the product of gaps between consecutive 1s
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