Split array in three equal sum subarrays
Mon Feb 07 2022 15:33:54 GMT+0000 (Coordinated Universal Time)
Saved by @Uttam #java #gfg #geeksforgeeks #lecture #arrays #prefixsum #subarrays #splitarray
Check if a given array can be divided into three parts with equal sum Consider an array A of n integers. Determine if array A can be split into three consecutive parts such that sum of each part is equal. If yes then print any index pair(i, j) such that sum(arr[0..i]) = sum(arr[i+1..j]) = sum(arr[j+1..n-1]), otherwise print -1. Examples: Input : arr[] = {1, 3, 4, 0, 4} Output : (1, 2) Sum of subarray arr[0..1] is equal to sum of subarray arr[2..3] and also to sum of subarray arr[4..4]. The sum is 4. Input : arr[] = {2, 3, 4} Output : -1 No three subarrays exist which have equal sum. --------------------------------------------------------------------------------------------------------- A simple solution is to first find all the subarrays, store the sum of these subarrays with their starting and ending points, and then find three disjoint continuous subarrays with equal sum. Time complexity of this solution will be quadratic. An efficient solution is to first find the sum S of all array elements. Check if this sum is divisible by 3 or not. This is because if sum is not divisible then the sum cannot be split in three equal sum sets. If there are three contiguous subarrays with equal sum, then sum of each subarray is S/3. Suppose the required pair of indices is (i, j) such that sum(arr[0..i]) = sum(arr[i+1..j]) = S/3. Also sum(arr[0..i]) = preSum[i] and sum(arr[i+1..j]) = preSum[j] – preSum[i]. This gives preSum[i] = preSum[j] – preSum[i] = S/3. This gives preSum[j] = 2*preSum[i]. Thus, the problem reduces to find two indices i and j such that preSum[i] = S/3 and preSum[j] = 2*(S/3). For finding these two indices, traverse the array and store sum upto current element in a variable preSum. Check if preSum is equal to S/3 and 2*(S/3).
https://www.geeksforgeeks.org/split-array-three-equal-sum-subarrays/
Comments