'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));
Solution 1:[1]
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]
};
Solution 2:[2]
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.
Search for consecutive indices.
Just iterate from index
1until 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));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));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kokodoko |
| Solution 2 | Nina Scholz |
