3Sum Closest

Two pointer

Problem

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the 
target is 2. (-1 + 2 + 1 = 2).
Input: [1, 0, 1, 1], target=100
Output: 3
Explanation: The triplet [1, 1, 1] has the 
closest sum to the target.

Solution

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        targetDiff = float("inf")
        
        for i in range(len(nums)-2):
            left = i+1
            right = len(nums)-1
            
            while left < right:
                currSum = nums[i]+nums[left]+nums[right]
                
                if(currSum == target):
                    return currSum
                
                
                #we do abs because the currSum can be greater than target and since
                #we need the difference we do abs 
            
                elif abs(currSum - target) < abs(targetDiff - target):
                    targetDiff = currSum
                 
                #if we had duplicates, in here is where we would do the while loop
                #to check
                if(currSum < target):
                    left+=1
                elif(currSum > target):
                    right-=1
              
        return targetDiff

Last updated