Given an array of n integers, we have to partition the array into three segments such that all the segments have equal sum. Segment sum is the sum of all the elements in segment.
Input : 1, 3, 6, 2, 7, 1, 2, 8 Output : [1, 3, 6], [2, 7, 1], [2, 8] Input : 7, 6, 1, 7 Output : , [6, 1],  Input : 7, 6, 2, 7 Output : Cannot divide the array into segments
A simple solution is to consider all pairs of indexes and for every pair check if it divides array into three equal parts. If yes, then return true. Time complexity of this solution is O(n2)
An efficient approach is to use two auxiliary arrays and store the prefix and suffix array sum in these arrays respectively. We then use the two pointer approach, with variable ‘i’ pointing to starting of prefix array and variable ‘j’ pointing to the end of suffix array. If pre[i] > suf[j], then decrement ‘j’, otherwise increment ‘i’.
We maintain a variable whose value is the total sum of the array and whenever we encounter pre[i] = total_sum / 3 or suf[j] = total_sum / 3, we store the value of i or j respectively as segment boundaries.
First Segment : 1 3 6 Second Segment : 2 7 1 Third Segment : 2 8
Time Complexity : O(n)
Auxiliary Space : O(n)
- Partition an array such into maximum increasing segments
- Equal sum array partition excluding a given element
- Print equal sum sets of array (Partition problem) | Set 1
- Print equal sum sets of array (Partition Problem) | Set 2
- Check if it possible to partition in k subarrays with equal sum
- Check if a large number can be divided into two or more segments of equal sum
- Split the array into odd number of segments of odd lengths
- Maximum average sum partition of an array
- Find a partition point in array
- Optimal partition of an array into four parts
- Divide an array into k segments to maximize maximum of segment minimums
- Minimum toggles to partition a binary array so that it has first 0s then 1s
- Find an element in array such that sum of left array is equal to sum of right array
- Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
- For each element in 1st array count elements less than or equal to it in 2nd array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.