I'm currently working on my JavaScript by doing exercises on Codewars.com. I've been doing OK but I've come across this question and I can't figure out a way to optimize it. Here is the question:
Sum of Pairs
Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
sum_pairs([0, 0, -2, 3], 2)
# there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)
sum_pairs([10, 5, 2, 3, 7, 5], 10)
# ^-----------^ 5 + 5 = 10, indices: 1, 5
# ^--^ 3 + 7 = 10, indices: 3, 4 *
# * entire pair is earlier, and therefore is the correct answer
== [3, 7]
NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.
It's simple enough and my solution works, but times out after 12 seconds on the 10,000,000 elements test.
My solution:
function sum_pairs(numArray, num){
var nums = numArray;
var sum = num;
var resultsArray = [];
var result;
for(var i = 0; i < nums.length; i++){
for(var j = i+1; j < nums.length; j++){
if(nums[i] + nums[j] == sum){
resultsArray.push({resArray: [nums[i],nums[j]], weight: j});
}
}
}
if(resultsArray.length != 0){
var result = resultsArray.pop();
for(var i = 0; i < resultsArray.length; i++){
if(result.weight > resultsArray[i].weight){
result = resultsArray[i];
}
}
result = result.resArray;
}
return result;
}
Question:
How to optimize this code so that it doesn't time out. I'm just a beginner programming wise and I'm unsure what part(s) of my solution causes slowdown. I'm about to read up on Big O notation now, any other resources for learning about code optimization?