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

175
Views
2 questions about a solution Equal sides of an array

Question: Take an array with integers and 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. Let's say you are given the array {1,2,3,4,3,2,1}: Your function equalsides() will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.

One working solution I found online is

function findEvenIndex(arr)
{
    var left = 0, right = arr.reduce(function(pv, cv) { return pv + cv; }, 0);

    for(var i = 0; i < arr.length; i++) {
        if(i>0) {
           left =left+ arr[i-1];
        }
        right =right- arr[i];
        if(left == right) 
           return i;
    }
    return -1;
}

I am not able to explain the following two lines of code, any help would be appreciated!

  1. Why write if i>0 in in the first line in the for loop
  2. Why write i-1 in the line left = left + arr[i-1]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Well the if(i>0) is required, because, arrays can't have negative indexes in JS. and i-1 is required, because, you want to add elements to the left of the balance position to the left item, not including the balance position. Though I do believe, this is a better solution:

function findEvenIndex(arr){
    let left = 0, right = arr.reduce( (a,b) => (a+b), 0);
    for(let i in arr){
        right -= arr[i];
        if(right == left) return i;
        left += arr[i];
    }
    return -1;
}

Arguably it's the same code, but, this has only one if statement and is a bit more apparent. Hope this helped :-)

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!