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

179
Visualizações
Find the indices of a pair of consecutive elements from a given array whose sum equals a specific target number, if no pair is found, return {-1, -1]

I am writing a JavaScript function sumPair(numbers, target) to find the indices of a pair of consecutive elements from a given array whose sum equals a specific target number. The function should return an array of the indices of the pair of consecutive elements or the array [-1, -1] if a pair is not found. My function works if I don't need to return [-1, -1] when there is no pair found, but it returns [-1, -1] even if there is a pair.

var sumPair = function(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] == target) {
        return [i, j]

      } else if (nums[i] + nums[j] !== target) {
        return [-1, -1]
      }
    }

  }
};
document.write(sumPair([10, 20, 10, 40, 50, 60, 70, 30], 50));

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The main issue is that your else if statement is not inside the loop, however, if you put it in the loop, it would return false on the first false you get, rather than looping through the entire array.

Instead, return the base case, and if there is a match, you will return the match before the base case fires.

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<script type="text/javascript">

var sumPair = function(nums, target) {
    for(let i = 0; i < nums.length; i++){
        for(let j = i+1; j < nums.length; j++){
            if(nums[i] + nums[j] == target){
                return ([i, j])

            }
            
           
        }
        
    }
return([-1,-1])
};
document.write(sumPair([10,20,10,40,50,60,70,30],50));

</script>


</script>
</body>
</html>
about 4 years ago · Juan Pablo Isaza Relatório

0

You can leave out the second for loop, and just check for i+1

var sumPair = function(nums, target) {
  for (let i = 0; i < nums.length - 1; i++) {
    if(nums[i] + nums[i+1] == target) {
        return [nums[i], nums[i+1]]
    }
  }
  return [-1,-1]
};
about 4 years ago · Juan Pablo Isaza Relatório

0

This answer contains two solutions, one for searching the first two indices of consecutive (literally!) indices and another of two indices which sum of the values are the wanted value.

  1. Search for consecutive indices.

    Just iterate from index 1 until smaller than length of the array. Check the sum of previous item and actual item. return their indices.

    const
        sumPair = (nums, target) => {
            for (let i = 1; i < nums.length; i++) {
                if (nums[i - 1] + nums[i] === target) return [i - 1, i];
            }
            return [-1, -1];
        };
    
    console.log(sumPair([10, 20, 10, 40, 50, 60, 70, 30], 50));

  2. Search for some smaller indices.

    Start iterating from zero and store the first found index in an object and check if the sum is true.

    const
        sumPair = (nums, target) => {
            const indices = {};
            for (let i = 0; i < nums.length; i++) {
                if (nums[i] in indices) return [indices[nums[i]], i];
                indices[target - nums[i]] ??= i;
            }
            return [-1, -1];
        };
    
    console.log(sumPair([10, 20, 10, 40, 50, 60, 70, 30], 50));

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