LeetCode 3Sum

Link to Problem

Description: given an array of numbers, return all unique triplets that add up to 0

Pseudocode

  1. Sort the array

  2. Declare an empty array result

  3. Loop over the sorted array and for each iteration:
    within the loop . . .

  4. 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

  5. declare left equal to i + 1

  6. declare right and set to end of array

  7. declare a while loop, and while left is less than right:
    within the while loop . . .

  8. declare sum, which adds up nums at i, left, and right.

  9. 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.

  10. if the sum is greater than 0, we should lower our sum of i, left, and right by decreasing our right pointer. Check that our newly decreased right pointer is different than the previous right pointer

  11. If the sum is less than 0, we should increase our sum of i, left, and right by increasing our left pointer. Check that our newly increased left pointer is dfferent than our previous right pointer

  12. Exit the while loop

  13. Exit the for loop

  14. return 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;
};