×

Equal Sum

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

You have been given an array of numbers. You have to find out the element which divides the array in such a manner that the sum of the two parts will be equal.

Let’s take an example to understand it well:

Input- [ 2 6 3 4 1 4 5 3 3 ]

Output- 1

Explanation- In this example the number 1 divides the whole array in two parts which are (2, 6, 3, 4) and (4, 5, 3, 3). The sum of both parts is equal to 15. So the answer will be 1.

Algorithm

Step 1: Start

Step 2: The size of array is taken from the user

Step 3: Array is created

Step 4: A function is called.

Step 5: We use one main loop and two sub loops.

Step 6: For each element we will calculate the sum of two parts.

Step 7: If sums are equal then the element will be returned.

Step 8: The returned value will be printed.

Step 9: Stop.

Explanation of Algorithm

The approach is very simple. We traverse all the elements of the array. For each element we calculate the sum of left part and right part of the array. If we find an element for which left and right sum are same then the element will be printed.

Code-

//C++ program to find the element of an array which makes sum of the left array is equal to sum of the right array

Program in C++

#include <bits/stdc++.h>
#include <iostream>
using namespace std;


int findElement(int arr[], int n)
{
	for (int i = 1; i < n; i++) {
		int leftSum = 0;
		for (int j = i - 1; j >= 0; j--) {
			leftSum += arr[j];
		}


		int rightSum = 0;
		for (int k = i + 1; k < n; k++) {
			rightSum += arr[k];
		}


		if (leftSum == rightSum) {
			return arr[i];
		}
	}


	return -1;
}


int main()
{
	// Case 1
	int arr1[] = { 1, 4, 3, 3, 2, 5 ,6};
	int n1 = sizeof(arr1) / sizeof(arr1[0]);
	cout << findElement(arr1, n1) << "\n";


	// Case 2
	int arr2[] = { 8, 1, 4, 3, 3, 2, 5, 6, 4, 4};
	int n2 = sizeof(arr2) / sizeof(arr2[0]);
	cout << findElement(arr2, n2);
	return 0;
}

# Python to find the element of an array which makes sum of the left array is equal to sum of the right array

Program in Python

def findElement(arr, n):
	for i in range(1, n):
		leftSum = sum(arr[0:i])
		rightSum = sum(arr[i+1:])
		if(leftSum == rightSum):
			return arr[i]
	return -1


if __name__ == "__main__":


	# Case 1
	arr = [1, 4, 3, 3, 2, 5 ,6]
	n = len(arr)
	print(findElement(arr, n))


	# Case 2
	arr = [8, 1, 4, 3, 3, 2, 5, 6, 4, 4]
	n = len(arr)
	print(findElement(arr, n))

//java program to find the element of an array which makes sum of the left array is equal to sum of the right array

Program in Java

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
class bn {
	static int findElement(int arr[], int n)
	{
		List<Integer> list
			= Arrays.stream(arr).boxed().collect(
				Collectors.toList());
		for (int i = 1; i <= n; i++) {
			int leftSum = list.subList(0, i)
							.stream()
							.mapToInt(x -> x)
							.sum();
			int rightSum = list.subList(i + 1, n)
							.stream()
							.mapToInt(x -> x)
							.sum();


			if (leftSum == rightSum)
				return list.get(i);
		}
		return -1;
	}
	public static void main(String[] args)
	{
		// Case 1
		int arr1[] = { 1, 4, 3, 3, 2, 5 ,6};
		int n1 = arr1.length;
		System.out.println(findElement(arr1, n1));


		// Case 2
		int arr2[] = { 8, 1, 4, 3, 3, 2, 5, 6, 4, 4};
		int n2 = arr2.length;
		System.out.println(findElement(arr2, n2));
	}
}


<script>

// JavaScript program to find the element of an array which makes sum of the left array is equal to sum of the right array

Program in JavaScript

function findElement(arr , n)
	{
		for(i = 1; i < n; i++){
		let leftSum = 0;
		for(j = i-1; j >= 0; j--){
			leftSum += arr[j];
		}
		
		let rightSum = 0;
		for(k = i+1; k < n; k++){
			rightSum += arr[k];
		}


		if(leftSum === rightSum){
			return arr[i];
		}
		
		}
		
		return -1;
	}
	//Case 1
	var arr = [ 1, 4, 3, 3, 2, 5 ,6];
	var n = arr.length;
	document.write(findElement(arr, n));
	
	document.write("<br><br>")
	
	//Case 2
	var arr = [ 8, 1, 4, 3, 3, 2, 5, 6, 4, 4];
	var n = arr.length;
	document.write(findElement(arr, n));


</script>

//C# program to find the element of an array which makes sum of the left array is equal to sum of the right array

Program in C#

using System;
public class bn {
	static int findElement(int[] arr, int n)
	{
		for (int i = 1; i < n; i++) {
			int leftSum = 0;
			for (int j = i - 1; j >= 0; j--) {
				leftSum += arr[j];
			}


			int rightSum = 0;
			for (int k = i + 1; k < n; k++) {
				rightSum += arr[k];
			}


			if (leftSum == rightSum) {
				return arr[i];
			}
		}
		return -1;
	}
	static public void Main()
	{
		// Case 1
		int[] arr1 = { 1, 4, 3, 3, 2, 5 ,6};
		int n1 = arr1.Length;
		Console.WriteLine(findElement(arr1, n1));


		// Case 2
		int[] arr2 = { 8, 1, 4, 3, 3, 2, 5, 6, 4, 4};
		int n2 = arr2.Length;
		Console.WriteLine(findElement(arr2, n2));
	}
}

Output: 

Case 1: [1, 4, 3, 3, 2, 5 ,6]
Ans: 2
Case 2: [8, 1, 4, 3, 3, 2, 5, 6, 4, 4]
Ans: 2

Related Topics

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Data Structure Prefix to Postfix Conversion

Prefix to Postfix Conversion Prefix: As the name suggests if the operator placed before the operands called the prefix expression.  The form of prefix expression is (operator, operand1, operand2). Example:  *+EF-GH (Infix:...

2 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Given a Binary Tree Return All Root-to-Leaf Paths

Implementation #include <bits/stdc++.h> using namespace std; // A binary tree node generally consists of data, a pointer to the left and right child, and a pointer to the right child.  class __nod { public: int record; __nod* Lft; __nod*...

9 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Given a Binary Tree Print the Shortest Path

Implementation // Writing a program in C++ to find the shortest between the nodes i and j.  #include <bits/stdc++.h> using namespace std; // the given function will print the path between nodes i and...

7 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

25 minutes read.

Bubble Sort vs Quick Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Quick Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

AVL tree in data structure c++

AVL tree is generally known as the self-sustained and most balanced tree in the field of a binary search tree. It was also widely known as the height-balanced binary tree....

6 minutes read.