Skip to content

Instantly share code, notes, and snippets.

@pjcodesjs
Created March 12, 2023 04:58
Show Gist options
  • Save pjcodesjs/7ac5c84d81ddfa4e4ee39322a943a61b to your computer and use it in GitHub Desktop.
Save pjcodesjs/7ac5c84d81ddfa4e4ee39322a943a61b to your computer and use it in GitHub Desktop.
function findTriplets(arr) {
let result = [];
const n = arr.length;
// Sort the array
arr.sort((a, b) => a - b);
for(let i = 0; i < n - 2; i++) {
// Check for duplicates
if (i > 0 && arr[i] === arr[i-1]) {
continue;
}
let left = i + 1;
let right = n - 1;
while (left < right) {
const sum = arr[i] + arr[left] + arr[right];
if (sum === 0) {
result.push([arr[i], arr[left], arr[right]]);
left++;
right--;
// Check for duplicates
while (left < right && arr[left] === arr[left-1]) {
left++;
}
while (left < right && arr[right] === arr[right+1]) {
right--;
}
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
// Example usage:
const arr = [0, -1, 2, -3, 1];
const triplets = findTriplets(arr);
console.log(triplets); // Output: [[-3, 1, 2], [-1, 0, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment