LeetCode 3Sum

I enjoy all things related to full stack development ☕️
Description: given an array of numbers, return all unique triplets that add up to 0
Pseudocode
Sort the array
Declare an empty array
resultLoop 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
leftequal toi + 1declare
rightand set to end of arraydeclare a
whileloop, and while left is less than right:
within the while loop . . .declare
sum, which adds upnumsati,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, andrightby decreasing ourrightpointer. Check that our newly decreasedrightpointer is different than the previousrightpointerIf the sum is less than 0, we should increase our sum of
i,left, andrightby increasing ourleftpointer. Check that our newly increasedleftpointer is dfferent than our previousrightpointerExit the
whileloopExit the
forloopreturn
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;
};



