Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Equal sides of an array

Problem: find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.

My solution

function findEvenIndex(arr) {
  var sum = i => i.reduce((a, b) => a + b),
    l = arr.length;

  for (let j = 0; j <= l; j++) {
    if (sum(arr.slice(0, j - 1)) === sum(arr.slice(j, l))) {
      return j
    } else {
      continue;
    }
  }
  return -1

}
When I run findEvenIndex([1,2,3,4,3,2,1]), it doesn't return anything. Where is the error that prevents 3 from being returned in the case of this example?

I've set the for loop procedure as follows to see what's going on

  for(let j = 0; j <= arr.length; j++){
    var left = arr.slice(0, j-1), right = arr.slice(j)
    console.log(left, right)
  } 
/* returns 
[1] [3,4,3,2,1] 
[1,2] [4,3,2,1] 
[1,2,3] [3,2,1]
as expected
*/

However, when try to console.log the sum of these arrays:

function sum(i){ return i.reduce((a, b) => a+b)} 
    
    var l = arr.length;
  
  for(let j = 0; j <= l; j++){
    var left = arr.slice(0, j-1), right = arr.slice(j)
    console.log(sum(left), sum(right))
  }

Using the snippet above, findEvenIndex([1,2,3,4,3,2,1]) returns "15 16"?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

your for loop is going all the way to l where it should stop at l-1


This isn't needed:

} else {
  continue;
}

performance wise, you don't need to compute so many stuff each time.

An alternative would be to progressively sum elements before your pivot and check if it's equal to half of (sum of all elements minus pivot value)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!