Solve the Sherlock and Array problem in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right.

We have to write this function, it should take in an array of Numbers, and any such number exists in the array, it should return its index, otherwise it should return -1. So, let’s write the code for this function −

Example

const arr = [1, 2, 3, 4, 5, 7, 3];
const arr2 = [4, 6, 3, 4, 5, 2, 1];
const isSherlockArray = arr => {
   let sum = arr.reduce((acc, val) => acc+val);
   let leftSum = 0;
   for(let i = 0; i < arr.length; i++){
      sum -= arr[i];
      if(sum === leftSum){
         return i;
      };
      leftSum += arr[i];
   };
   return -1;
};
console.log(isSherlockArray(arr));
console.log(isSherlockArray(arr2));

Output

The output in the console will be −

4
-1
raja
Published on 28-Aug-2020 13:50:44
Advertisements