Find an element in array such that sum of left array is equal to sum of right array

Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sum.
Examples: 

Input: 1 4 2 5
Output: 2
Explanation: If 2 is the partition, 
      subarrays are : {1, 4} and {5}

Input: 2 3 4 1 4 5
Output: 1
Explanation: If 1 is the partition, 
 Subarrays are : {2, 3, 4} and {4, 5}

Method 1 (Simple) 
Consider every element starting from the second element. Compute the sum of elements on its left and sum of elements on its right. If these two sums are the same, return the element.

Method 2 (Using Prefix and Suffix Arrays : 

We form a prefix and suffix sum arrays

Given array: 1 4 2 5
Prefix Sum:  1  5 7 12
Suffix Sum:  12 11 7 5

Now, we will traverse both prefix arrays.
The index at which they yield equal result,
is the index where the array is partitioned 
with equal sum.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
 
int findElement(int arr[], int n)
{
    // Forming prefix sum array from 0
    int prefixSum[n];
    prefixSum[0] = arr[0];
    for (int i = 1; i < n; i++)
        prefixSum[i] = prefixSum[i - 1] + arr[i];
 
    // Forming suffix sum array from n-1
    int suffixSum[n];
    suffixSum[n - 1] = arr[n - 1];
    for (int i = n - 2; i >= 0; i--)
        suffixSum[i] = suffixSum[i + 1] + arr[i];
 
    // Find the point where prefix and suffix
    // sums are same.
    for (int i = 1; i < n - 1; i++)
        if (prefixSum[i] == suffixSum[i])
            return arr[i];
 
    return -1;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 4, 2, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findElement(arr, n);
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find an element
// such that sum of right side element
// is equal to sum of left side
public class GFG {
     
    // Finds an element in an array such that
    // left and right side sums are equal
    static int findElement(int arr[], int n)
    {
        // Forming prefix sum array from 0
        int[] prefixSum = new int[n];
        prefixSum[0] = arr[0];
        for (int i = 1; i < n; i++)
            prefixSum[i] = prefixSum[i - 1] + arr[i];
      
        // Forming suffix sum array from n-1
        int[] suffixSum = new int[n];
        suffixSum[n - 1] = arr[n - 1];
        for (int i = n - 2; i >= 0; i--)
            suffixSum[i] = suffixSum[i + 1] + arr[i];
      
        // Find the point where prefix and suffix
        // sums are same.
        for (int i = 1; i < n - 1; i++)
            if (prefixSum[i] == suffixSum[i])
                return arr[i];
      
        return -1;
    }
      
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 4, 2, 5 };
        int n = arr.length;
        System.out.println(findElement(arr, n));
    }
}
// This code is contributed by Sumit Ghosh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 Program to find an element
# such that sum of right side element
# is equal to sum of left side
 
# Function for Finds an element in
# an array such that left and right
# side sums are equal
def findElement(arr, n) :
     
    # Forming prefix sum array from 0
    prefixSum = [0] * n
    prefixSum[0] = arr[0]
    for i in range(1, n) :
        prefixSum[i] = prefixSum[i - 1] + arr[i]
 
    # Forming suffix sum array from n-1
    suffixSum = [0] * n
    suffixSum[n - 1] = arr[n - 1]
    for i in range(n - 2, -1, -1) :
        suffixSum[i] = suffixSum[i + 1] + arr[i]
 
    # Find the point where prefix
    # and suffix sums are same.
    for i in range(1, n - 1, 1) :
        if prefixSum[i] == suffixSum[i] :
            return arr[i]
         
    return -1
 
# Driver Code
if __name__ == "__main__" :
     
    arr = [ 1, 4, 2, 5]
    n = len(arr)
    print(findElement(arr, n))
 
# This code is contributed by ANKITRAI1
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find an element
// such that sum of right side element
// is equal to sum of left side
using System;
 
class GFG
{
     
    // Finds an element in an
    // array such that left
    // and right side sums
    // are equal
    static int findElement(int []arr,
                           int n)
    {
        // Forming prefix sum
        // array from 0
        int[] prefixSum = new int[n];
        prefixSum[0] = arr[0];
        for (int i = 1; i < n; i++)
            prefixSum[i] = prefixSum[i - 1] +
                                     arr[i];
     
        // Forming suffix sum
        // array from n-1
        int[] suffixSum = new int[n];
        suffixSum[n - 1] = arr[n - 1];
        for (int i = n - 2; i >= 0; i--)
            suffixSum[i] = suffixSum[i + 1] +
                                     arr[i];
     
        // Find the point where prefix
        // and suffix sums are same.
        for (int i = 1; i < n - 1; i++)
            if (prefixSum[i] == suffixSum[i])
                return arr[i];
     
        return -1;
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = { 1, 4, 2, 5 };
        int n = arr.Length;
        Console.WriteLine(findElement(arr, n));
    }
}
 
// This code is contributed by anuj_67.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
function findElement(&$arr, $n)
{
    // Forming prefix sum array from 0
    $prefixSum = array_fill(0, $n, NULL);
    $prefixSum[0] = $arr[0];
    for ($i = 1; $i < $n; $i++)
        $prefixSum[$i] = $prefixSum[$i - 1] +
                                    $arr[$i];
 
    // Forming suffix sum array from n-1
    $suffixSum = array_fill(0, $n, NULL);
    $suffixSum[$n - 1] = $arr[$n - 1];
    for ($i = $n - 2; $i >= 0; $i--)
        $suffixSum[$i] = $suffixSum[$i + 1] +
                                    $arr[$i];
 
    // Find the point where prefix
    // and suffix sums are same.
    for ($i = 1; $i < $n - 1; $i++)
        if ($prefixSum[$i] == $suffixSum[$i])
            return $arr[$i];
 
    return -1;
}
 
// Driver code
$arr = array( 1, 4, 2, 5 );
$n = sizeof($arr);
echo findElement($arr, $n);
 
// This code is contributed
// by ChitraNayal
?>
chevron_right

Output

2






Method 3 (Space efficient) 
We calculate the sum of the whole array except the first element in right_sum, considering it to be the partitioning element. Now, we traverse the array from left to right, subtracting an element from right_sum and adding an element to left_sum. At the point where right_sum equals left_sum, we get the partition.

Below is the implementation :  

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
 
// Function to compute partition
int findElement(int arr[], int size)
{
    int right_sum = 0, left_sum = 0;
 
    // Computing right_sum
    for (int i = 1; i < size; i++)
        right_sum += arr[i];
 
    // Checking the point of partition
    // i.e. left_Sum == right_sum
    for (int i = 0, j = 1; j < size; i++, j++) {
        right_sum -= arr[j];
        left_sum += arr[i];
 
        if (left_sum == right_sum)
            return arr[i + 1];
    }
 
    return -1;
}
 
// Driver
int main()
{
    int arr[] = { 2, 3, 4, 1, 4, 5 };
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << findElement(arr, size);
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find an element
// such that sum of right side element
// is equal to sum of left side
public class GFG {
     
    // Function to compute partition
    static int findElement(int arr[], int size)
    {
        int right_sum = 0, left_sum = 0;
      
        // Computing right_sum
        for (int i = 1; i < size; i++)
            right_sum += arr[i];
      
        // Checking the point of partition
        // i.e. left_Sum == right_sum
        for (int i = 0, j = 1; j < size; i++, j++) {
            right_sum -= arr[j];
            left_sum += arr[i];
      
            if (left_sum == right_sum)
                return arr[i + 1];
        }
      
        return -1;
    }
      
    // Driver
    public static void main(String args[])
    {
        int arr[] = { 2, 3, 4, 1, 4, 5 };
        int size = arr.length;
        System.out.println(findElement(arr, size));
    }
}
// This code is contributed by Sumit Ghosh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 Program to find an element
# such that sum of right side element
# is equal to sum of left side
 
# Function to compute partition
def findElement(arr, size) :
 
    right_sum, left_sum = 0, 0
 
    # Computing right_sum
    for i in range(1, size) :
        right_sum += arr[i]
 
    i, j = 0, 1
 
    # Checking the point of partition
    # i.e. left_Sum == right_sum
    while j < size :
        right_sum -= arr[j]
        left_sum += arr[i]
 
        if left_sum == right_sum :
            return arr[i + 1]
 
        j += 1
        i += 1
 
    return -1
 
# Driver Code
if __name__ == "__main__" :
     
    arr = [ 2, 3, 4, 1, 4, 5]
    n = len(arr)
    print(findElement(arr, n))
 
# This code is contributed by ANKITRAI1
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find an
// element such that sum
// of right side element
// is equal to sum of
// left side
using System;
 
class GFG
{
    // Function to compute
    // partition
    static int findElement(int []arr,
                           int size)
    {
        int right_sum = 0,
            left_sum = 0;
     
        // Computing right_sum
        for (int i = 1; i < size; i++)
            right_sum += arr[i];
     
        // Checking the point
        // of partition i.e.
        // left_Sum == right_sum
        for (int i = 0, j = 1;
                 j < size; i++, j++)
        {
            right_sum -= arr[j];
            left_sum += arr[i];
     
            if (left_sum == right_sum)
                return arr[i + 1];
        }
     
        return -1;
    }
     
    // Driver Code
    public static void Main()
    {
        int []arr = {2, 3, 4, 1, 4, 5};
        int size = arr.Length;
        Console.WriteLine(findElement(arr, size));
    }
}
 
// This code is contributed
// by anuj_67.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// Function to compute partition
function findElement(&$arr, $size)
{
    $right_sum = 0;
    $left_sum = 0;
 
    // Computing right_sum
    for ($i = 1; $i < $size; $i++)
        $right_sum += $arr[$i];
 
    // Checking the point of partition
    // i.e. left_Sum == right_sum
    for ($i = 0, $j = 1;
         $j < $size; $i++, $j++)
    {
        $right_sum -= $arr[$j];
        $left_sum += $arr[$i];
 
        if ($left_sum == $right_sum)
            return $arr[$i + 1];
    }
 
    return -1;
}
 
// Driver Code
$arr = array( 2, 3, 4, 1, 4, 5 );
$size = sizeof($arr);
echo findElement($arr, $size);
 
// This code is contributed
// by ChitraNayal
?>
chevron_right

Output
1






Method 4 (Both Time and Space Efficient)

We define two pointers i and j to traverse the array from left and right,
left_sum and right_sum to store sum from right and left respectively

If left_sum is lesser than increment i and if right_sum is lesser than decrement j 
and, find a position where left_sum == right_sum and i and j are next to each other




Note: This solution is only applicable if the array contains only positive elements.

Below is the implementation of the above approach: 

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find an element
// such that sum of right side element
// is equal to sum of left side
#include<bits/stdc++.h>
using namespace std;
     
// Function to compute
// partition
int findElement(int arr[],
                int size)
{
  int right_sum = 0,
      left_sum = 0;
   
  // Maintains left
  // cumulative sum
  left_sum = 0;
 
  // Maintains right
  // cumulative sum
  right_sum = 0;
  int i = -1, j = -1;
 
  for(i = 0, j = size - 1;
      i < j; i++, j--)
  {
    left_sum += arr[i];
    right_sum += arr[j];
 
    // Keep moving i towards
    // center until left_sum
    //is found lesser than right_sum
    while(left_sum < right_sum &&
          i < j)
    {
      i++;
      left_sum += arr[i];
    }
     
    // Keep moving j towards
    // center until right_sum is
    // found lesser than left_sum
    while(right_sum < left_sum &&
          i < j)
    {
      j--;
      right_sum += arr[j];
    }
  }
   
  if(left_sum == right_sum)
    return arr[i];
  else
    return -1;
}
 
// Driver code
int main()
{
  int arr[] = {2, 3, 4,
               1, 4, 5};
  int size = sizeof(arr) /
             sizeof(arr[0]);
  cout << (findElement(arr, size));
}
 
// This code is contributed by shikhasingrajput
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find an element
// such that sum of right side element
// is equal to sum of left side
public class Gfg {
     
    // Function to compute partition
    static int findElement(int arr[], int size)
    {
        int right_sum = 0, left_sum = 0;
        // Maintains left cumulative sum
        left_sum = 0;
         
        // Maintains right cumulative sum
        right_sum=0;
        int i = -1, j = -1;
         
        for( i = 0, j = size-1 ; i < j ; i++, j-- ){
            left_sum += arr[i];
            right_sum += arr[j];
             
            // Keep moving i towards center until
            // left_sum is found lesser than right_sum
            while(left_sum < right_sum && i < j){
                i++;
                left_sum += arr[i];
            }
            // Keep moving j towards center until
            // right_sum is found lesser than left_sum
            while(right_sum < left_sum && i < j){
                j--;
                right_sum += arr[j];
            }
        }
        if(left_sum == right_sum)
            return arr[i];
        else
            return -1;
    }
     
    // Driver code
    public static void main(String args[])
    {
        int arr[] = {2, 3, 4, 1, 4, 5};
        int size = arr.length;
        System.out.println(findElement(arr, size));
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find an element
# such that sum of right side element
# is equal to sum of left side
 
# Function to compute partition
def findElement(arr, size):
   
    # Maintains left cumulative sum
    left_sum = 0;
 
    # Maintains right cumulative sum
    right_sum = 0;
    i = 0; j = -1;
    j = size - 1;
     
    while(i < j):
        if(i < j):
            left_sum += arr[i];
            right_sum += arr[j];
 
            # Keep moving i towards center
            # until left_sum is found
            # lesser than right_sum
            while (left_sum < right_sum and
                   i < j):
                i += 1;
                left_sum += arr[i];
 
            # Keep moving j towards center
            # until right_sum is found
            # lesser than left_sum
            while (right_sum < left_sum and
                   i < j):
                j -= 1;
                right_sum += arr[j];
            j -= 1
            i += 1
    if (left_sum == right_sum):
        return arr[i];
    else:
        return -1;
 
# Driver code
if __name__ == '__main__':
   
    arr = [2, 3, 4,
           1, 4, 5];
    size = len(arr);
    print(findElement(arr, size));
 
# This code is contributed by shikhasingrajput
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find an element
// such that sum of right side element
// is equal to sum of left side
using System;
 
class GFG{
     
// Function to compute partition
static int findElement(int []arr, int size)
{
    int right_sum = 0, left_sum = 0;
     
    // Maintains left cumulative sum
    left_sum = 0;
     
    // Maintains right cumulative sum
    right_sum = 0;
    int i = -1, j = -1;
     
    for(i = 0, j = size - 1; i < j; i++, j--)
    {
        left_sum += arr[i];
        right_sum += arr[j];
         
        // Keep moving i towards center until
        // left_sum is found lesser than right_sum
        while (left_sum < right_sum && i < j)
        {
            i++;
            left_sum += arr[i];
        }
         
        // Keep moving j towards center until
        // right_sum is found lesser than left_sum
        while (right_sum < left_sum && i < j)
        {
            j--;
            right_sum += arr[j];
        }
    }
    if (left_sum == right_sum)
        return arr[i];
    else
        return -1;
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 2, 3, 4, 1, 4, 5 };
    int size = arr.Length;
     
    Console.WriteLine(findElement(arr, size));
}
}
 
// This code is contributed by Amit Katiyar
chevron_right

Output: 

1




Since all loops start traversing from the last updated i and j pointers and do not cross each other, they run n times in the end.

Time Complexity – O(n) 
Auxiliary Space – O(1)

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Recommended Posts:


Article Tags :