Ways to Split Array Into Good Subarrays Problem
Description
LeetCode Problem 2750.
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 10^9 + 7.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [0,1,0,0,1]
Output: 3
Explanation: There are 3 ways to split nums into good subarrays:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]
Example 2:
Input: nums = [0,1,0]
Output: 1
Explanation: There is 1 way to split nums into good subarrays:
- [0,1,0]
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 1
Solution
Approach: Multiplication principle
Each good subarray holds exactly one 1, so every cut must lie somewhere between two consecutive 1s. If those 1s are at indices j < i, the cut can go in any of the i - j gaps between them (right after j, ..., right before i), and the choices for different pairs are independent. Multiply i - j over all consecutive pairs of 1s, modulo 10^9 + 7. If the array has no 1, the answer is 0.
Complexity: O(n) time and O(1) space.
class Solution:
def numberOfGoodSubarraySplits(self, nums: List[int]) -> int:
mod = 10**9 + 7
ans, j = 1, -1
for i, x in enumerate(nums):
if x == 0:
continue
if j > -1:
ans = ans * (i - j) % mod
j = i
return 0 if j == -1 else ans