I am currently utilizing three loops to tackle this problem, but the complexity is O(n3). Is there a way to achieve this with a lower complexity level?
Sharing a JS Fiddle code snippet for the three loops approach:
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var sum = 8;
find(arr, sum);
function find(arr, sum) {
var found = false;
for (var x = 0; x < arr.length - 3; x++) {
for (var y = x + 1; y < arr.length - 2; y++) {
for (var z = y + 1; z < arr.length; z++) {
if (arr[x] + arr[y] + arr[z] == sum) {
found = true;
break;
}
}
}
}
if (found) {
console.log("found");
} else {
console.log("not found");
}
}