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

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

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 Denunciar

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 Denunciar

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 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