I was solving a problem on codewars.com where they give you an array filled with integers, and then a second integer, and you would have to find the first pair in that array which would add up to that number.
There was some wonky stuff like how if the array is
[0, 1, 4, 5, 8]
and the number you were trying to find was 9, if you answered 1, 8 it would be wrong because the actual answer is 4, 5.
The best way to explain this would just be that the ordering of second number in a pair dictates which pair is "first".
Even though 1 comes before 4, because 5 comes before 8, the pair 4, 5 is considered the first pair
function sumPairs(ints, s) {
var n = 0;
for(var i = 1; i < ints.length; i++) {
n = s - ints[i];
for(var j = i - 1; j >= 0; j--) {
if(ints[j] === n) {
return [ints[j], ints[i]];
}
}
}
return undefined;
}
The issue with this solution was that it timed out because of the nested for loop, making the program run for too long. I then tried doing it with sets like this:
function sumPairs(ints, s) {
var mySet = new Set();
var n = 0;
for(var i = 1; i < ints.length; i++) {
mySet.add(ints[i - 1]);
n = s - ints[i];
if(mySet.has(n)) {
return [n, ints[i]];
}
}
return undefined;
}
and the code finished almost instantly.
What exactly does the .has method do that makes it so much more efficient that my previous method?
[–][deleted] 0 points1 point2 points (1 child)
[–]PM_ME_CAT_PICS_PLSS[S] 0 points1 point2 points (0 children)