Ways to Split Array Into Good Subarrays — LeetCode 2750 Python Solution

MediumArrayMathDynamic Programming
Problem
#2750
Reading time
2 min

The 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.

Example

Input
nums = [0,1,0,0,1]
Output
3
Explanation
There are 3 ways to split nums into good subarrays:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2750. Ways to Split Array Into Good Subarrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2750. Ways to Split Array Into Good Subarrays?
LeetCode 2750. Ways to Split Array Into Good Subarrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 2750. Ways to Split Array Into Good Subarrays?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2750. Ways to Split Array Into Good Subarrays?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2750. Ways to Split Array Into Good Subarrays cover?
LeetCode 2750. Ways to Split Array Into Good Subarrays is tagged Array, Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview