#1712
Ways to Split Array Into Three Subarrays
MediumArrayTwo PointersBinary SearchPrefix SumPrefix SumTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a prefix sum array and two pointers to efficiently count valid splits. By iterating through the right boundary of the mid subarray, we can find the valid left boundaries using a single pass.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the prefix sum array for the input array.
- 2Step 2: Initialize two pointers: one for the left boundary and one for the mid boundary.
- 3Step 3: For each position of the mid boundary, adjust the left boundary to maintain the conditions for a good split.
- 4Step 4: Count the number of valid splits for each mid boundary position.
solution.py18 lines
1# Full working Python code
2
3def waysToSplit(nums):
4 MOD = 10**9 + 7
5 n = len(nums)
6 prefix_sum = [0] * (n + 1)
7 for i in range(n):
8 prefix_sum[i + 1] = prefix_sum[i] + nums[i]
9 count = 0
10 left = 0
11 for mid in range(1, n - 1):
12 while left < mid and prefix_sum[left + 1] <= prefix_sum[mid + 1] - prefix_sum[1]:
13 left += 1
14 right = mid
15 while right < n - 1 and prefix_sum[mid + 1] <= prefix_sum[right + 1]:
16 right += 1
17 count += right - mid
18 return count % MODℹ
Complexity note: The time complexity is O(n) because we only pass through the array a constant number of times. The space complexity is O(n) due to the prefix sum array storing cumulative sums.
- 1Using prefix sums allows for efficient subarray sum calculations.
- 2Two pointers can help maintain the conditions for valid splits without redundant checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.