Skip to content

2750. Ways to Split Array Into Good Subarrays 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int numberOfGoodSubarraySplits(vector<int>& nums) {
    if (ranges::count(nums, 1) == 0)
      return 0;

    constexpr int kMod = 1'000'000'007;
    int prev = -1;  // the previous index of 1
    int ans = 1;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] == 1) {
        if (prev != -1)
          ans = ans * static_cast<long>(i - prev) % kMod;
        prev = i;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int numberOfGoodSubarraySplits(int[] nums) {
    if (Arrays.stream(nums).filter(num -> num == 1).count() == 0)
      return 0;

    final int kMod = 1_000_000_007;
    int prev = -1; // the previous index of 1
    int ans = 1;

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] == 1) {
        if (prev != -1)
          ans = (int) ((long) ans * (i - prev) % kMod);
        prev = i;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def numberOfGoodSubarraySplits(self, nums: list[int]) -> int:
    if 1 not in nums:
      return 0

    kMod = 1_000_000_007
    prev = -1  # the previous index of 1
    ans = 1

    for i, num in enumerate(nums):
      if num == 1:
        if prev != -1:
          ans *= i - prev
          ans %= kMod
        prev = i

    return ans