3Sum Closest

Problem Id: 16 Difficulty: Medium Tag: Array Tag: Two Pointers


Intuition

Almost the same as 15. 3Sum. Could be solved using two pointers.

Solution


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        closest = float('inf')
        for i in range(len(nums) - 2):
            j = i + 1
            k = len(nums) - 1
            while j < k:
                s = nums[i] + nums[j] + nums[k]
                if abs(s - target) < abs(closest - target):
                    closest = s

                if s >= target:
                    k -= 1
                else:
                    j += 1
        return closest