Array ( [0] => [1] => questions [2] => Arrays [3] => Balanced-Array ) Arrays | Balanced Array | THE INQUISITIVE





Balanced Array

LEVEL:Beginner

Description

Given an array of integers. You have to find the index such that sum of elements of left side of index is equal to sum of elements of right side of index. If it is not found print -1.

Input Format

First line contains the size of the first array. Next line contains the m integers separated by the spaces.

Output Format

Return the position of index.


Example 1:

Input
6
6 3 1 2 7 2
Output
2
Example 2:

Input
9
9 12 6 4 1 17 6 4 4 
Output
4
Example 3:

Input
7
13 6 8 3 3  7 6
Output
2

oops

Login to see Discussion




Approach

Approach1: Brute Force

Step-i) Iterate a for loop with a variable i.
Step-ii) initialize 2 variables l,r as 0.
Step-iii) Iterate other loop from 0 to i and add all the elements into l.
Step-iv) Iterate other loop from i+1 to length of array and add all the elements into r.
Step-v) Check if l==r and return i, if equal.

Time Complexity: O(n^2)
Space Complexity: O(n)

Approach2:

Step-i) First find the sum of all elements in the array and store it in sum.
Step-ii) Initialize 2 variables l and r to 0.
Step-iii) Iterate through the array with elements a.
Step-iv) Add element a to l and subtract a from r.
Step-v) If at a point l==r, return i.

Time Complexity: O(n)
Space Compelxity: O(n)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution