Skip to main content
Back to problems
#2750
Medium Algorithms

Ways to split array into good subarrays

Array Math Dynamic Programming
34.8% acceptance
Feb 25, 2026
469
14
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn number_of_good_subarray_splits(nums: Vec<i32>) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let mut ans: i64 = 1;
    let mut last_one: i64 = -1;
    let mut found = false;
    for (i, &v) in nums.iter().enumerate() {
      if v == 1 {
        if found {
          // gap between this 1 and last 1
          ans = (ans * (i as i64 - last_one)) % MOD;
        }
        found = true;
        last_one = i as i64;
      }
    }
    if !found { 0 } else { ans as i32 }
  }
}