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
- Partition the array in K segments such that bitwise AND of individual segment sum is maximized
- 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
- Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
- Check if a large number can be divided into two or more segments of equal sum
- Check if it possible to partition in k subarrays with equal sum
- Find Partition Line such that sum of values on left and right is equal
- Maximum sum of the array after dividing it into three segments
- Split the array into odd number of segments of odd lengths
- Divide the array in K segments such that the sum of minimums is maximized
- Divide an array into k segments to maximize maximum of segment minimums
- Find a partition point in array
- Optimal partition of an array into four parts
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.