I have the following function:
function myFunction(array, sum){
for(var i = 0; i < array.length; i++){
var firstValue = array[i];
for(var x = i + 1; x < array.length; x++){
var secondValue = array[x];
if((firstValue + secondValue) == sum){
return i + ": " + x;
}
}
}
return "No two array values match the sum";
}
The above takes two parameters; first an array and the second a sum. It finds the first two numbers in the array that when added sums to the second parameter. The array indexes of the two numbers that sum to the second parameter is then returned. Right now, the above function solves the problem in n^2 time. Is there a way to solve the same problem in kn time?
I wrote the function in JavaScript, but this can apply to all modern languages.