I'm trying to wrap my head around saving time in my coding solution.
I have a function called tripletSum
which takes two parameters x
and a
where x
is a number and a
is an array.
This function is supposed to return true
if the list a
contains three elements which add up to the number x
, otherwise it should return false
.
I've 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 doesn't seem like the best practice. Currently the time it takes to run through this function is O(n^3)
if I'm not mistaken and I think it can be improved to have a time complexity of O(n^2)
.
Anyway I can change this code to do that?
Edit: This is not a duplicate of the other question because I was asking for a specific improvement on my current example in JavaScript which is not what it asked in the marked duplicate question.