KatInterview

15. 3Sum

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all unique triplets in a given array of integers nums that sum up to zero. The key challenges are:

Solution

3Sum in Python

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        result = []
        n = len(nums)
        if n < 3:
            return result

        # Sort the array to use the two-pointer technique
        nums.sort()

        for i in range(n - 2):
            # If the first element is positive, no need to continue
            # since the array is sorted, the sum will always be positive.
            if nums[i] > 0:
                break

            # Skip duplicate elements for the first number of the triplet
            if i > 0 and nums[i] == nums[i - 1]:
                continue

            left, right = i + 1, n - 1
            target = -nums[i]

            while left < right:
                current_sum = nums[left] + nums[right]

                if current_sum == target:
                    # Found a triplet
                    result.append([nums[i], nums[left], nums[right]])

                    # Skip duplicates for the second and third numbers
                    while left < right and nums[left] == nums[left + 1]:
                        left += 1
                    while left < right and nums[right] == nums[right - 1]:
                        right -= 1

                    # Move pointers to find the next unique pair
                    left += 1
                    right -= 1
                elif current_sum < target:
                    # Sum is too small, move left pointer to the right
                    left += 1
                else: # current_sum > target
                    # Sum is too large, move right pointer to the left
                    right -= 1
        
        return result

3Sum in Java

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length < 3) {
            return result;
        }

        // Sort the array to use the two-pointer technique
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            // If the first element is positive, no need to continue
            // since the array is sorted, the sum will always be positive.
            if (nums[i] > 0) {
                break;
            }

            // Skip duplicate elements for the first number of the triplet
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int left = i + 1;
            int right = nums.length - 1;
            int target = -nums[i];

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

                if (sum == target) {
                    // Found a triplet
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));

                    // Skip duplicates for the second number
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    // Skip duplicates for the third number
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }

                    // Move pointers to find the next unique pair
                    left++;
                    right--;
                } else if (sum < target) {
                    // Sum is too small, move left pointer to the right
                    left++;
                } else { // sum > target
                    // Sum is too large, move right pointer to the left
                    right--;
                }
            }
        }

        return result;
    }
}

3Sum in C++

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        int n = nums.size();
        if (n < 3) {
            return result;
        }

        // Sort the array to use the two-pointer technique
        sort(nums.begin(), nums.end());

        for (int i = 0; i < n - 2; ++i) {
            // If the first element is positive, no need to continue
            // since the array is sorted, the sum will always be positive.
            if (nums[i] > 0) {
                break;
            }

            // Skip duplicate elements for the first number of the triplet
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int left = i + 1;
            int right = n - 1;
            int target = -nums[i];

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

                if (sum == target) {
                    // Found a triplet
                    result.push_back({nums[i], nums[left], nums[right]});

                    // Skip duplicates for the second number
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    // Skip duplicates for the third number
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }

                    // Move pointers to find the next unique pair
                    left++;
                    right--;
                } else if (sum < target) {
                    // Sum is too small, move left pointer to the right
                    left++;
                } else { // sum > target
                    // Sum is too large, move right pointer to the left
                    right--;
                }
            }
        }

        return result;
    }
};

3Sum in TypeScript

function threeSum(nums: number[]): number[][] {
    const result: number[][] = [];
    const n = nums.length;
    if (n < 3) {
        return result;
    }

    // Sort the array to use the two-pointer technique
    // The default sort is lexicographical, so we need a compare function.
    nums.sort((a, b) => a - b);

    for (let i = 0; i < n - 2; i++) {
        // If the first element is positive, no need to continue
        // since the array is sorted, the sum will always be positive.
        if (nums[i] > 0) {
            break;
        }

        // Skip duplicate elements for the first number of the triplet
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue;
        }

        let left = i + 1;
        let right = n - 1;
        const target = -nums[i];

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

            if (sum === target) {
                // Found a triplet
                result.push([nums[i], nums[left], nums[right]]);

                // Skip duplicates for the second number
                while (left < right && nums[left] === nums[left + 1]) {
                    left++;
                }
                // Skip duplicates for the third number
                while (left < right && nums[right] === nums[right - 1]) {
                    right--;
                }

                // Move pointers to find the next unique pair
                left++;
                right--;
            } else if (sum < target) {
                // Sum is too small, move left pointer to the right
                left++;
            } else { // sum > target
                // Sum is too large, move right pointer to the left
                right--;
            }
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.