Description: given an array of numbers, return all unique triplets that add up to 0
Pseudocode
Sort the array
Declare an empty array
result
Loop over the sorted array and for each iteration:
within the loop . . .Check if the index is greater than 0 and if the number at index is equal to the number at the previous index - if it is, continue
declare
left
equal toi + 1
declare
right
and set to end of arraydeclare a
while
loop, and while left is less than right:
within the while loop . . .declare
sum
, which adds upnums
ati
,left
, andright
.If the sum is 0, push the unique values into result array and deduct right / increase left, handling unique cases like we did in step 1 of the loop.
if the sum is greater than 0, we should lower our sum of
i
,left
, andright
by decreasing ourright
pointer. Check that our newly decreasedright
pointer is different than the previousright
pointerIf the sum is less than 0, we should increase our sum of
i
,left
, andright
by increasing ourleft
pointer. Check that our newly increasedleft
pointer is dfferent than our previousright
pointerExit the
while
loopExit the
for
loopreturn
result
Code:
var threeSum = function(nums) {
nums.sort((a, b) => a - b);
let result = [];
for (let i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.push([nums[i], nums[left], nums[right]]);
right--;
while (nums[right] === nums[right + 1]) right--;
left++;
while (nums[left] === nums[left - 1]) left++;
}
if (sum > 0) {
right--;
while (nums[right] === nums[right + 1]) right--;
}
if (sum < 0) {
left++;
while (nums[left] === nums[left - 1]) left++;
}
}
}
return result;
};