878150. Split array in three equal sum subarrays
Split Array in Three Equal Sum Subarrays
Summary
The problem is to split an array into three contiguous subarrays such that each subarray has the same sum. This requires finding a way to divide the array into three parts, ensuring that each part's sum is equal. The key concept involved is prefix sums, which are used to efficiently calculate the total sum of each possible subarray.
Detailed Explanation
To solve this problem, we can start by calculating the total sum of the array and then iterating through the array with a sliding window approach. For each window, we calculate the sum of the elements within it using prefix sums. This allows us to quickly determine if the current window's sum is equal to one-third of the total sum.
Here's a step-by-step breakdown of the solution:
- Calculate the total sum of the array.
- Initialize three variables:
left,mid, andrightto represent the sums of the left, middle, and right subarrays, respectively. - Iterate through the array with a sliding window approach:
- For each window, calculate the prefix sum using the current element and the previous prefix sum.
- Check if the current window's sum is equal to one-third of the total sum.
- If it is, update
left,mid, andrightaccordingly based on which part of the array the current window falls into (left, middle, or right).
- Once the iteration is complete, return the three subarrays corresponding to
left,mid, andright.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only use a constant amount of space to store the prefix sum and the three subarray sums.
Optimized Solutions
Java
public static int[][] splitArray(int[] arr) {
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
int leftSum = 0, midSum = 0, rightSum = totalSum;
for (int i = 0; i < arr.length; i++) {
if (leftSum == rightSum / 3) return new int[][]{Arrays.copyOfRange(arr, 0, i + 1), Arrays.copyOfRange(arr, i + 1, midIndex), Arrays.copyOfRange(arr, midIndex, arr.length)};
if (leftSum < rightSum / 3) leftSum += arr[i];
else rightSum -= arr[i];
}
return new int[][]{Arrays.copyOfRange(arr, 0, midIndex), Arrays.copyOfRange(arr, midIndex, midIndex + 1), Arrays.copyOfRange(arr, midIndex + 1, arr.length)};
}