3Sum in TypeScript

function threeSum(nums: number[]): number[][] {
    // First, sort the array. This makes it possible to use a two-pointer approach.
    nums.sort((a, b) => a - b);

    const result: number[][] = [];

    // Iterate over the array, considering each element as the first element of the potential triplet
    for (let i = 0; i < nums.length - 2; i++) {
        // Skip duplicate values to avoid duplicate triplets
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue;
        }

        // Initialize two pointers
        let left = i + 1;
        let right = nums.length - 1;

        while (left < right) {
            const sum = nums[i] + nums[left] + nums[right];

            // Check if the sum of the triplet is zero
            if (sum === 0) {
                result.push([nums[i], nums[left], nums[right]]);

                // Skip duplicates for the 'left' pointer
                while (left < right && nums[left] === nums[left + 1]) {
                    left++;
                }

                // Skip duplicates for the 'right' pointer
                while (left < right && nums[right] === nums[right - 1]) {
                    right--;
                }

                // Move both pointers for the next potential triplet
                left++;
                right--;
            } else if (sum < 0) {
                // If the sum is less than zero, move the 'left' pointer to increase the sum
                left++;
            } else {
                // If the sum is greater than zero, move the 'right' pointer to decrease the sum
                right--;
            }
        }
    }

    return result;
}

PrevNext