Split Array with Equal Sum Problem
Description
LeetCode Problem 548.
Given an integer array nums of length n, return true if there is a triplet (i, j, k) which satisfies the following conditions:
0 < i, i + 1 < j, j + 1 < k < n - 1- The sum of subarrays
(0, i - 1),(i + 1, j - 1),(j + 1, k - 1)and(k + 1, n - 1)is equal.
A subarray (l, r) represents a slice of the original array starting from the element indexed l to the element indexed r.
Example 1:
Input: nums = [1,2,1,2,1,2,1]
Output: true
Explanation:
i = 1, j = 3, k = 5.
sum(0, i - 1) = sum(0, 0) = 1
sum(i + 1, j - 1) = sum(2, 2) = 1
sum(j + 1, k - 1) = sum(4, 4) = 1
sum(k + 1, n - 1) = sum(6, 6) = 1
Example 2:
Input: nums = [1,2,1,2,1,2,1,2]
Output: false
Constraints:
n == nums.length1 <= n <= 2000-10^6 <= nums[i] <= 10^6
Solution
Approach: Fix the Middle Cut, Meet in the Middle
Trying every triplet (i, j, k) takes O(n3) checks. The middle cut j splits the problem into two independent halves, which brings it down to O(n2).
First build prefix sums, s[x] = nums[0] + ... + nums[x-1], so that any subarray sum is a difference of two entries: the four parts are s[i], s[j] - s[i+1], s[k] - s[j+1] and s[n] - s[k+1].
Now fix j:
- Left half. For every valid
i(1 <= i < j - 1), check whether the first two parts are equal,s[i] == s[j] - s[i+1]. If so, put that common sum into a set. The set holds every sumtfor whichnums[0..j-1]can be cut into two parts of sumt. - Right half. For every valid
k(j + 2 <= k < n - 1), check whether the last two parts are equal. If they are, and their sum is also in the set, all four parts are equal: returntrue.
The halves only need to agree on the sum, not on where their cuts are, which is why a set is enough. Each j costs O(n), so the whole search is O(n2).
The bounds encode the rule that the four parts are non-empty and the cut elements are skipped: i >= 1, j >= i + 2, k >= j + 2 and k <= n - 2. So j runs from 3 to n - 4, and any array with fewer than 7 elements returns false. Values can be negative, so a part can have sum 0 or less; nothing here relies on sums being positive.
Complexity: O(n2) time. O(n) space for the prefix sums and the set.
class Solution:
def splitArray(self, nums: List[int]) -> bool:
n = len(nums)
s = [0] * (n + 1) # s[x] = nums[0] + ... + nums[x - 1]
for x, v in enumerate(nums):
s[x + 1] = s[x] + v
for j in range(3, n - 3):
# sums that split nums[0..j-1] into two equal parts around some i
left = set()
for i in range(1, j - 1):
if s[i] == s[j] - s[i + 1]:
left.add(s[i])
# an equal split of nums[j+1..n-1] around some k with the same sum
for k in range(j + 2, n - 1):
third, fourth = s[k] - s[j + 1], s[n] - s[k + 1]
if third == fourth and third in left:
return True
return False