Created
March 12, 2023 04:58
-
-
Save pjcodesjs/7ac5c84d81ddfa4e4ee39322a943a61b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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