-
-
Save vishal7201/7f7a60b89b947cbe7cd857924e2f9310 to your computer and use it in GitHub Desktop.
Balance the Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Michael gives an array A={a1, a2,. .., aN} to Dwight. Michael then asks Dwight to find out whether there exists an element | |
| in the array such that the sum of elements on its left is equal to the sum of elements on its right. | |
| In other words, is there an index i such that, a1+a2...ai-1 = ai+1+ai+2...aN. | |
| Complete the function balanceSum to help Dwight answer that question. | |
| Note: If there are no elements to the left or to the right, then that sum is considered to be zero. | |
| Constraints | |
| 1 ≤ N ≤ 105 | |
| 1 ≤ Ai ≤ 2x104 where 1 ≤ i ≤ N | |
| Input Format | |
| The first line contains a single integer N, the number of elements in array arr. | |
| The next N lines for each test case contains N integers that comprise the array arr. | |
| Output Format | |
| return 1 if there exists an element in the array such that the sum of elements to its left is equal to the sum | |
| of elements to its right. Otherwise, return 0. | |
| 4 | |
| 1 | |
| 2 | |
| 3 | |
| 3 | |
| // function isArray_Balanced(arr) { | |
| // for ( var i=0; i<arr.length; i++) { | |
| // var leftSum = arr.slice(0,i).sum(); | |
| // var rightSum = arr.slice(i+1).sum(); | |
| // if(leftSum === rightSum) { | |
| // return 1; | |
| // } | |
| // } | |
| // return 0; | |
| // } | |
| // Array.prototype.sum = function() { | |
| // this.reduce((sum, num) => sum +num , 0); | |
| // }; | |
| // built in object , the array has a new method, this sum method | |
| // array prototype , an instance of an array shares the array methods | |
| // Method 2 | |
| function isArray_Balanced(arr) { | |
| var left = 0 ; | |
| var right = arr.sum(); | |
| for ( var i=0 ; i < arr.length; i++) { | |
| right -= arr[i]; | |
| if(left === right) { | |
| return 1; | |
| } | |
| left += arr[i]; | |
| } | |
| return 0; | |
| } | |
| Array.prototype.sum = function() { | |
| this.reduce((sum, num) => sum +num , 0); | |
| }; | |
| isArray_Balanced([1,2,3,3]) | |
| //substract from the rght, then compare, add to left |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment