Find Closest Sum of Three Numbers in a List To a Target

Given an array of integers, and a target integer, find the three numbers whose sum is the closes to the target variable. We do not need to return the actuals numbers that add up or their indices, but just need to return the sum which is closes to the target value. This is a problem from leetcode at this link .

Solution: Using 2 pointers

class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() N = len(nums) ref_diff = 1000000 return_val = target for idx,i in enumerate(nums): if idx>0 and nums[idx]==nums[idx-1]: continue left_pointer = idx+1 right_pointer = N-1 while left_pointer < right_pointer: summ = i + nums[left_pointer] + nums[right_pointer] diff = abs(target - summ) if diff < ref_diff: ref_diff = diff return_val = summ if summ > target: right_pointer -= 1 elif summ < target: left_pointer += 1 else: break return return_val