KatInterview

259. 3Sum Smaller

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 the number of triplets (i, j, k) from an array nums such that i < j < k and nums[i] + nums[j] + nums[k] < target. A brute-force approach would involve three nested loops to check every possible triplet, leading to an O(n³) time complexity. Given that n can be up to 3500, this would be too slow. We need a more efficient approach.

Solution

3Sum Smaller in Python

class Solution:
    def threeSumSmaller(self, nums: List[int], target: int) -> int:
        n = len(nums)
        # If there are fewer than 3 elements, no triplet can be formed.
        if n < 3:
            return 0

        # Sort the array. This is crucial for the two-pointer approach.
        # Time complexity for sorting is O(n log n).
        nums.sort()

        count = 0

        # Iterate through the array to fix the first element of the triplet.
        # We only need to go up to n-3 because we need at least two more elements.
        for i in range(n - 2):
            # Use two pointers for the remaining part of the array.
            left, right = i + 1, n - 1

            # The new target for the pair (nums[left], nums[right])
            new_target = target - nums[i]

            while left < right:
                # If the sum of the pair is less than the new target
                if nums[left] + nums[right] < new_target:
                    # If nums[left] + nums[right] < new_target, then for the current nums[left],
                    # all elements from nums[left+1] to nums[right] will also form a valid pair
                    # with nums[left] because the array is sorted.
                    # The number of such pairs is (right - (left + 1) + 1) = right - left.
                    count += (right - left)
                    
                    # We have found all triplets for the current `i` and `left`. Move to the next `left`.
                    left += 1
                else:
                    # If the sum is not smaller, it's too large. We need to decrease the sum.
                    # To do that, we move the right pointer to a smaller element.
                    right -= 1
        
        return count

3Sum Smaller in Java

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        // Get the size of the array
        int n = nums.length;
        // If there are fewer than 3 elements, no triplet can be formed.
        if (n < 3) {
            return 0;
        }

        // Sort the array. This is crucial for the two-pointer approach.
        // Time complexity for sorting is O(n log n).
        Arrays.sort(nums);

        int count = 0;

        // Iterate through the array to fix the first element of the triplet.
        // We only need to go up to n-3 because we need at least two more elements.
        for (int i = 0; i < n - 2; i++) {
            // Use two pointers for the remaining part of the array.
            int left = i + 1;
            int right = n - 1;

            while (left < right) {
                int currentSum = nums[i] + nums[left] + nums[right];
                
                // If the sum of the triplet is less than the target
                if (currentSum < target) {
                    // If nums[i] + nums[left] + nums[right] < target, then for the current i and left,
                    // all elements from index left+1 to right will also form a valid triplet with nums[i] and nums[left]
                    // because the array is sorted (nums[k] <= nums[right] for k between left and right).
                    // The number of such triplets is (right - (left + 1) + 1) = right - left.
                    count += (right - left);
                    
                    // We have found all triplets for the current `i` and `left`. Move to the next `left`.
                    left++;
                } else {
                    // If the sum is not smaller, it's too large. We need to decrease the sum.
                    // To do that, we move the right pointer to a smaller element.
                    right--;
                }
            }
        }

        return count;
    }
}

3Sum Smaller in C++

class Solution {
public:
    int threeSumSmaller(vector<int>& nums, int target) {
        // Get the size of the array
        int n = nums.size();
        // If there are fewer than 3 elements, no triplet can be formed.
        if (n < 3) {
            return 0;
        }

        // Sort the array. This is crucial for the two-pointer approach.
        // Time complexity for sorting is O(n log n).
        sort(nums.begin(), nums.end());

        int count = 0;

        // Iterate through the array to fix the first element of the triplet.
        // We only need to go up to n-3 because we need at least two more elements.
        for (int i = 0; i < n - 2; ++i) {
            // Use two pointers for the remaining part of the array.
            int left = i + 1;
            int right = n - 1;

            // The new target for the pair (nums[left], nums[right])
            int newTarget = target - nums[i];

            while (left < right) {
                // If the sum of the pair is less than the new target
                if (nums[left] + nums[right] < newTarget) {
                    // If nums[left] + nums[right] < newTarget, then for the current nums[left],
                    // all elements from nums[left+1] to nums[right] will also form a valid pair
                    // with nums[left] because the array is sorted.
                    // The number of such pairs is (right - (left + 1) + 1) = right - left.
                    count += (right - left);
                    // Move to the next element on the left to find more triplets.
                    left++;
                } else {
                    // If the sum is not smaller, it's too large. We need to decrease the sum.
                    // To do that, we move the right pointer to a smaller element.
                    right--;
                }
            }
        }

        return count;
    }
};

3Sum Smaller in TypeScript

function threeSumSmaller(nums: number[], target: number): number {
    const n = nums.length;
    // If there are fewer than 3 elements, no triplet can be formed.
    if (n < 3) {
        return 0;
    }

    // Sort the array. Note: default sort is lexicographical, so a comparator is needed for numbers.
    // Time complexity for sorting is O(n log n).
    nums.sort((a, b) => a - b);

    let count = 0;

    // Iterate through the array to fix the first element of the triplet.
    // We only need to go up to n-3 because we need at least two more elements.
    for (let i = 0; i < n - 2; i++) {
        // Use two pointers for the remaining part of the array.
        let left = i + 1;
        let right = n - 1;

        // The new target for the pair (nums[left], nums[right])
        const newTarget = target - nums[i];

        while (left < right) {
            // If the sum of the pair is less than the new target
            if (nums[left] + nums[right] < newTarget) {
                // If nums[left] + nums[right] < newTarget, then for the current nums[left],
                // all elements from nums[left+1] to nums[right] will also form a valid pair
                // with nums[left] because the array is sorted.
                // The number of such pairs is (right - (left + 1) + 1) = right - left.
                count += (right - left);
                
                // We have found all triplets for the current `i` and `left`. Move to the next `left`.
                left++;
            } else {
                // If the sum is not smaller, it's too large. We need to decrease the sum.
                // To do that, we move the right pointer to a smaller element.
                right--;
            }
        }
    }

    return count;
};

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.