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.

Algorithm Approach

The efficient approach is to:

  • Calculate the total sum of the array
  • Iterate through each element, maintaining a left sum
  • For each position, check if left sum equals right sum (total - left - current element)
  • Return the index if found, otherwise return -1

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 

4
-1

How It Works

For array [1, 2, 3, 4, 5, 7, 3]:

  • At index 4 (element 5): left sum = 1+2+3+4 = 10, right sum = 7+3 = 10
  • Since left sum equals right sum, function returns index 4

For array [4, 6, 3, 4, 5, 2, 1]:

  • No index satisfies the condition, so function returns -1

Step-by-Step Breakdown

const detailedSherlock = arr => {
    let totalSum = arr.reduce((acc, val) => acc + val);
    let leftSum = 0;
    
    console.log(`Array: [${arr.join(', ')}]`);
    console.log(`Total sum: ${totalSum}`);
    
    for(let i = 0; i 

Array: [1, 2, 3, 4, 5, 7, 3]
Total sum: 25
Index 0: leftSum=0, rightSum=24
Index 1: leftSum=1, rightSum=22
Index 2: leftSum=3, rightSum=19
Index 3: leftSum=6, rightSum=15
Index 4: leftSum=10, rightSum=10
Result: 4

Edge Cases

// Single element array
console.log(isSherlockArray([1])); // 0 (left=0, right=0)

// Two element array  
console.log(isSherlockArray([1, 1])); // -1

// Array with zeros
console.log(isSherlockArray([0, 0, 0])); // 0, 1, or 2 (all valid)

// Empty array
console.log(isSherlockArray([])); // -1
0
-1
1
-1

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of array
  • Space Complexity: O(1) as we only use constant extra space

Conclusion

The Sherlock and Array problem efficiently finds an equilibrium index where left and right sums are equal. The solution uses a single pass approach with O(n) time complexity, making it optimal for large arrays.

Updated on: 2026-03-15T23:18:59+05:30

734 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements