Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda