I am trying to wrap my head around saving time in my coding solution.
I have a function with a name tripletSumthat takes two parameters xand a, where xis a number, and ais an array.
This function should return trueif the list acontains three elements that contain a number x, otherwise it should return false.
I created the following working solution:
function tripletSum(x, a) {
for(var i = 0; i < a.length; i++) {
for(var j = i + 1; j < a.length; j++) {
for(var k = j + 1; k < a.length; k++) {
if((a[i] + a[j] + a[k]) === x) {
return true;
}
}
}
}
return false;
}
But this does not seem to be the best practice. Currently, the time spent on performing this function is O(n^3), if I am not mistaken, and I think that it can be improved in order to have temporary complexity O(n^2).
Anyway, can I change this code to do this?
: , JavaScript, , .