 Open in App
Not now

# Split array in three equal sum subarrays

• Difficulty Level : Medium
• Last Updated : 18 Feb, 2023

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).

Steps to solve this problem:

1. The first step is to find the sum of the entire array and store it in the variable S.

2. Check if the sum of the array S is divisible by 3. If not, return 0, indicating that the array cannot be split into three equal sum sets.

3. Calculate S/3 and store it in the variable S1 and calculate 2 * (S/3) and store it in the variable S2. These variables represent the sum of each of the three sets.

4. Initialize the variables ind1 and ind2 to store the indices which have prefix sum divisible by S/3. Set these variables to -1 initially.

5. Loop through the elements of the array, keeping track of the prefix sum, until the second last index. This is because the S2 should not be at the last index.

6. If the prefix sum is equal to S/3, store the current index in ind1. If the prefix sum is equal to 2 * (S/3), store the current index in ind2. If both ind1 and ind2 are found, break out of the loop.

7. If both indices ind1 and ind2 are found, print them as the two indices which divide the array into three equal sum sets. Return 1, indicating that the array can be split into three equal sum sets.

8. If the indices ind1 and ind2 are not found, return 0, indicating that the array cannot be split into three equal sum sets.

9. Finally, in the main function, call the findSplit function with the given array and its size. If the function returns 0, print -1.

Implementation:

## C++

 `// CPP program to determine if array arr[]``// can be split into three equal sum sets.``#include ``using` `namespace` `std;` `// Function to determine if array arr[]``// can be split into three equal sum sets.``int` `findSplit(``int` `arr[], ``int` `n)``{``    ``int` `i;` `    ``// variable to store prefix sum``    ``int` `preSum = 0;` `    ``// variables to store indices which``    ``// have prefix sum divisible by S/3.``    ``int` `ind1 = -1, ind2 = -1;` `    ``// variable to store sum of``    ``// entire array.``    ``int` `S;` `    ``// Find entire sum of the array.``    ``S = arr;``    ``for` `(i = 1; i < n; i++)``        ``S += arr[i];` `    ``// Check if array can be split in``    ``// three equal sum sets or not.``    ``if` `(S % 3 != 0)``        ``return` `0;` `    ``// Variables to store sum S/3``    ``// and 2*(S/3).``    ``int` `S1 = S / 3;``    ``int` `S2 = 2 * S1;` `    ``// Loop until second last index``    ``// as S2 should not be at the last``    ``for` `(i = 0; i < n - 1; i++) {``        ``preSum += arr[i];` `        ``// If prefix sum is equal to S/3``        ``// store current index.``        ``if` `(preSum == S1 && ind1 == -1)``            ``ind1 = i;` `        ``// If prefix sum is equal to 2* (S/3)``        ``// store current index.``        ``else` `if` `(preSum == S2 && ind1 != -1) {``            ``ind2 = i;` `            ``// Come out of the loop as both the``            ``// required indices are found.``            ``break``;``        ``}``    ``}` `    ``// If both the indices are found``    ``// then print them.``    ``if` `(ind1 != -1 && ind2 != -1) {``        ``cout << ``"("` `<< ind1 << ``", "` `<< ind2 << ``")"``;``        ``return` `1;``    ``}` `    ``// If indices are not found return 0.``    ``return` `0;``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 1, 3, 4, 0, 4 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``if` `(findSplit(arr, n) == 0)``        ``cout << ``"-1"``;``    ``return` `0;``}`

## C

 `// C program to determine if array arr[] can be split into``// three equal sum sets.``#include ` `// Function to determine if array arr[] can be split into``// three equal sum sets.``int` `findSplit(``int` `arr[], ``int` `n)``{``    ``int` `i;` `    ``// variable to store prefix sum``    ``int` `preSum = 0;` `    ``// variables to store indices which have prefix sum``    ``// divisible by S/3.``    ``int` `ind1 = -1, ind2 = -1;` `    ``// variable to store sum of entire array.``    ``int` `S;` `    ``// Find entire sum of the array.``    ``S = arr;``    ``for` `(i = 1; i < n; i++)``        ``S += arr[i];` `    ``// Check if array can be split in three equal sum sets``    ``// or not.``    ``if` `(S % 3 != 0)``        ``return` `0;` `    ``// Variables to store sum S/3 and 2*(S/3).``    ``int` `S1 = S / 3;``    ``int` `S2 = 2 * S1;` `    ``// Loop until second last index as S2 should not be at``    ``// the last``    ``for` `(i = 0; i < n - 1; i++) {``        ``preSum += arr[i];` `        ``// If prefix sum is equal to S/3 store current``        ``// index.``        ``if` `(preSum == S1 && ind1 == -1)``            ``ind1 = i;` `        ``// If prefix sum is equal to 2* (S/3) store current``        ``// index.``        ``else` `if` `(preSum == S2 && ind1 != -1) {``            ``ind2 = i;` `            ``// Come out of the loop as both the required``            ``// indices are found.``            ``break``;``        ``}``    ``}` `    ``// If both the indices are found then print them.``    ``if` `(ind1 != -1 && ind2 != -1) {``        ``printf``(``"(%d,%d)"``, ind1, ind2);``        ``return` `1;``    ``}` `    ``// If indices are not found return 0.``    ``return` `0;``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 1, 3, 4, 0, 4 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``if` `(findSplit(arr, n) == 0)``        ``printf``(``"-1"``);``    ``return` `0;``}` `// This code is contributed by Aditya Kumar (adityakumar129)`

## Java

 `// Java program to determine if array arr[]``// can be split into three equal sum sets.``import` `java.io.*;``import` `java.util.*;` `public` `class` `GFG {` `    ``// Function to determine if array arr[]``    ``// can be split into three equal sum sets.``    ``static` `int` `findSplit(``int``[] arr, ``int` `n)``    ``{``        ``int` `i;` `        ``// variable to store prefix sum``        ``int` `preSum = ``0``;` `        ``// variables to store indices which``        ``// have prefix sum divisible by S/3.``        ``int` `ind1 = -``1``, ind2 = -``1``;` `        ``// variable to store sum of``        ``// entire array.``        ``int` `S;` `        ``// Find entire sum of the array.``        ``S = arr[``0``];``        ``for` `(i = ``1``; i < n; i++)``            ``S += arr[i];` `        ``// Check if array can be split in``        ``// three equal sum sets or not.``        ``if` `(S % ``3` `!= ``0``)``            ``return` `0``;` `        ``// Variables to store sum S/3``        ``// and 2*(S/3).``        ``int` `S1 = S / ``3``;``        ``int` `S2 = ``2` `* S1;` `        ``// Loop until second last index``        ``// as S2 should not be at the last``        ``for` `(i = ``0``; i < n - ``1``; i++) {``            ``preSum += arr[i];` `            ``// If prefix sum is equal to S/3``            ``// store current index.``            ``if` `(preSum == S1 && ind1 == -``1``)``                ``ind1 = i;` `            ``// If prefix sum is equal to 2*(S/3)``            ``// store current index.``            ``else` `if` `(preSum == S2 && ind1 != -``1``) {``                ``ind2 = i;` `                ``// Come out of the loop as both the``                ``// required indices are found.``                ``break``;``            ``}``        ``}` `        ``// If both the indices are found``        ``// then print them.``        ``if` `(ind1 != -``1` `&& ind2 != -``1``) {``            ``System.out.print(``"("` `+ ind1 + ``", "` `+ ind2``                             ``+ ``")"``);``            ``return` `1``;``        ``}` `        ``// If indices are not found return 0.``        ``return` `0``;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String args[])``    ``{``        ``int``[] arr = { ``1``, ``3``, ``4``, ``0``, ``4` `};``        ``int` `n = arr.length;``        ``if` `(findSplit(arr, n) == ``0``)``            ``System.out.print(``"-1"``);``    ``}``}` `// This code is contributed by Aditya Kumar (adityakumar129)`

## Python3

 `# Python3 program to determine if array arr[]``# can be split into three equal sum sets.` `# Function to determine if array arr[]``# can be split into three equal sum sets.``def` `findSplit(arr, n):``    ``# variable to store prefix sum``    ``preSum ``=` `0` `    ``# variables to store indices which``    ``# have prefix sum divisible by S/3.``    ``ind1 ``=` `-``1``    ``ind2 ``=` `-``1` `    ``# variable to store sum of``    ``# entire array. S` `    ``# Find entire sum of the array.``    ``S ``=` `arr[``0``]``    ``for` `i ``in` `range``(``1``, n):``        ``S ``+``=` `arr[i]` `    ``# Check if array can be split in``    ``# three equal sum sets or not.``    ``if``(S ``%` `3` `!``=` `0``):``        ``return` `0``    ` `    ``# Variables to store sum S/3``    ``# and 2*(S/3).``    ``S1 ``=` `S ``/` `3``    ``S2 ``=` `2` `*` `S1` `    ``# Loop until second last index``    ``# as S2 should not be at the last``    ``for` `i ``in` `range``(``0``,n``-``1``):``        ``preSum ``+``=` `arr[i]``        ` `        ``# If prefix sum is equal to S/3``        ``# store current index.``        ``if` `(preSum ``=``=` `S1 ``and` `ind1 ``=``=` `-``1``):``            ``ind1 ``=` `i``        ``# If prefix sum is equal to 2*(S/3)``        ``# store current index.       ``        ``elif``(preSum ``=``=` `S2 ``and` `ind1 !``=` `-``1``):``            ``ind2 ``=` `i``            ` `            ``# Come out of the loop as both the``            ``# required indices are found.``            ``break`    `    ``# If both the indices are found``    ``# then print them.``    ``if` `(ind1 !``=` `-``1` `and` `ind2 !``=` `-``1``):``        ``print` `(``"({}, {})"``.``format``(ind1,ind2))``        ``return` `1``    ` `    ``# If indices are not found return 0.``    ``return` `0` `# Driver code``arr ``=` `[ ``1``, ``3``, ``4``, ``0``, ``4` `]``n ``=` `len``(arr)``if` `(findSplit(arr, n) ``=``=` `0``) :``    ``print` `(``"-1"``)``# This code is contributed by Manish Shaw``# (manishshaw1)`

## C#

 `// C# program to determine if array arr[]``// can be split into three equal sum sets.``using` `System;``using` `System.Collections.Generic;` `class` `GFG {``    ` `    ``// Function to determine if array arr[]``    ``// can be split into three equal sum sets.``    ``static` `int` `findSplit(``int` `[]arr, ``int` `n)``    ``{``        ``int` `i;``    ` `        ``// variable to store prefix sum``        ``int` `preSum = 0;``    ` `        ``// variables to store indices which``        ``// have prefix sum divisible by S/3.``        ``int` `ind1 = -1, ind2 = -1;``    ` `        ``// variable to store sum of``        ``// entire array.``        ``int` `S;``    ` `        ``// Find entire sum of the array.``        ``S = arr;``        ``for` `(i = 1; i < n; i++)``            ``S += arr[i];``    ` `        ``// Check if array can be split in``        ``// three equal sum sets or not.``        ``if``(S % 3 != 0)``            ``return` `0;``        ` `        ``// Variables to store sum S/3``        ``// and 2*(S/3).``        ``int` `S1 = S / 3;``        ``int` `S2 = 2 * S1;``    ` `        ``// Loop until second last index``        ``// as S2 should not be at the last``        ``for` `(i = 0; i < n-1; i++)``        ``{``            ``preSum += arr[i];``            ` `        ``// If prefix sum is equal to S/3``        ``// store current index.``            ``if` `(preSum ==  S1 && ind1 == -1)``                ``ind1 = i;``            ` `        ``// If prefix sum is equal to S/3``        ``// store current index.``            ``else` `if``(preSum == S2 && ind1 != -1)``            ``{``                ``ind2 = i;``                ` `                ``// Come out of the loop as both the``                ``// required indices are found.``                ``break``;``            ``}``        ``}``    ` `        ``// If both the indices are found``        ``// then print them.``        ``if` `(ind1 != -1 && ind2 != -1)``        ``{``            ``Console.Write(``"("` `+ ind1 + ``", "``                             ``+ ind2 + ``")"``);``            ``return` `1;``        ``}``    ` `        ``// If indices are not found return 0.``        ``return` `0;``    ``}``    ` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``int` `[]arr = { 1, 3, 4, 0, 4 };``        ``int` `n = arr.Length;``        ``if` `(findSplit(arr, n) == 0)``            ``Console.Write(``"-1"``);``    ``}``}` `// This code is contributed by Manish Shaw``// (manishshaw1)`

## PHP

 ``

## Javascript

 ``

Output

`(1, 2)`

Complexity Analysis:

• Time Complexity: O(n)
• Auxiliary Space: O(1)

My Personal Notes arrow_drop_up