# GeetCode Hub

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.

Example 1:

```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).
```

Constraints:

• `3 <= nums.length <= 10^3`
• `-10^3 <= nums[i] <= 10^3`
• `-10^4 <= target <= 10^4`

class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() min_ = abs(sum(nums[0:3])-target) res = nums[0:3] for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue l, r = i+1, len(nums)-1 while l < r: s = nums[i] + nums[l] + nums[r] if s-target<0: if target-s < min_: min_ = target-s res = [nums[i], nums[l], nums[r]] l += 1 else: if s-target < min_: min_ = s-target res = [nums[i], nums[l], nums[r]] r -= 1 return sum(res)

The main gist of this question is to reduce the 3 sum problem into a 2 sum problem and using the two-pointer approach to solve it.

Time Complexity: O(n^2)
Space Complexity: O(1)

Medium
Medium