I am trying to solve a problem where, 

> 
> Given an array S of n integers, find three integers in S such that the
>  sum is closest to a given number, target. Return the sum of the three
>  integers. You may assume that each input would have exactly one
>  solution.
> 
> 
> 
> ```
> For example, given array S = {-1 2 1 -4}, and target = 1.
> 
> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
> 
> ```
> 
> 

My solution is: take a number out (number\_1) from the array, set the target to target - that number and find two other numbers which are closest to the new target. This way: number\_1 + number\_2 + number\_3 will be closest as number\_2 + number\_3 will be closest to target - number\_1.

I tried my solution at <https://leetcode.com/problems/3sum-closest/description/>.

My solution is:

```
def threeSumClosest(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    """
    closest_sum = nums[0] + nums[1] + nums[2]

    for i in range(len(nums)):

        # Create temp array excluding a number

        if i!=len(nums)-1:
            temp = nums[:i] + nums[i+1:]

        else:
            temp = nums[:len(nums)-1]

        # Sort the temp array and set new target to target - the excluded number

        temp = sorted(temp)            
        l, r = 0, len(temp) -1 
        t = target - nums[i]

        while(l<r):

            if temp[l] + temp[r] == t:
                return target

            elif temp[l] + temp[r] > t:

                if abs(temp[l] + temp[r] + nums[i] - target) < abs(closest_sum - target):
                    closest_sum = temp[l] + temp[r] + nums[i]

                r = r - 1

            else:

                if abs(temp[l] + temp[r] + nums[i] - target) < abs(closest_sum - target):
                    closest_sum = temp[l] + temp[r] + nums[i]

                l = l + 1

        return closest_sum

```

It passes 80 test cases out of 125, so the solution logic looks fine enough for me.

It fails for:

```
Input:
[0,2,1,-3]
1
Output:
3
Expected:
0

```

Can't understand why it fails and how to make my logic consistent.

Thanks for your help.