#2750

Ways to Split Array Into Good Subarrays

Medium
ArrayMathDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach identifies the positions of '1's and calculates the number of ways to split the array based on the gaps between them. This reduces the problem to linear time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Identify the indices of all '1's in the array.
  2. 2Step 2: Calculate the gaps between consecutive '1's to determine how many zeros are between them.
  3. 3Step 3: For each gap, the number of ways to split is (gap + 1) because you can place a split before each zero.
  4. 4Step 4: Multiply the number of ways for all gaps together and return the result modulo 10^9 + 7.
solution.py12 lines
1# Full working Python code
2
3def count_good_splits(nums):
4    MOD = 10**9 + 7
5    indices = [i for i, x in enumerate(nums) if x == 1]
6    if len(indices) == 0:
7        return 0
8    ways = 1
9    for i in range(1, len(indices)):
10        gap = indices[i] - indices[i-1] - 1
11        ways = (ways * (gap + 1)) % MOD
12    return ways

Complexity note: This complexity is linear because we only traverse the array a couple of times: once to find indices of '1's and once to calculate the gaps.

  • 1Identifying key positions (indices of '1's) simplifies the problem.
  • 2The number of ways to split is determined by the gaps between '1's.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.