← Back to Leo Academy Masterclass

Problem #16: 3Sum Closest

Medium Two Pointers

Intuition & Strategy Breakdown

Sort the array and fix one element. Use two pointers to find two other elements such that their sum is closest to target, updating the closest sum whenever a smaller difference is found.

Python Solution

class Solution:
    def threeSumClosest(self, nums: list[int], target: int) -> int:
        nums.sort()
        closest = float("inf")
        for i in range(len(nums) - 2):
            l, r = i + 1, len(nums) - 1
            while l < r:
                curr_sum = nums[i] + nums[l] + nums[r]
                if abs(curr_sum - target) < abs(closest - target):
                    closest = curr_sum
                if curr_sum < target:
                    l += 1
                elif curr_sum > target:
                    r -= 1
                else:
                    return curr_sum
        return closest

Java Solution

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closest = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int l = i + 1, r = nums.length - 1;
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (Math.abs(sum - target) < Math.abs(closest - target)) {
                    closest = sum;
                }
                if (sum < target) l++;
                else if (sum > target) r--;
                else return target;
            }
        }
        return closest;
    }
}
Watch Interactive Video on Leo Academy Main App