
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Solve the Sherlock and Array problem in JavaScript
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
- Related Articles
- Solution for array reverse algorithm problem JavaScript
- C++ Program to Solve the Dominating Set Problem
- C++ Program to Solve the Fractional Knapsack Problem
- How we Can Solve this Problem
- 10 ways to solve the problem of computer illiteracy
- C++ Program to Solve the 0-1 Knapsack Problem
- C++ Program to Solve N-Queen Problem
- How to solve the diamond problem using default methods in Java?
- Parse and balance angle brackets problem in JavaScript
- What is file hierarchy structure and how does it solve the naming problem?
- The algorithm problem - Backtracing pattern in JavaScript
- Python Program to solve Maximum Subarray Problem using Divide and Conquer
- Snail Trail Problem in JavaScript
- Recursive Staircase problem in JavaScript
- Distributing Bananas Problem in JavaScript

Advertisements