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)