Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda