3Sum Closest

Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that their 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
Inputnums = [-1,2,1,-4], target = 1
Output2
The sum closest to 1 is 2, formed by -1 + 2 + 1.
Example 2
Inputnums = [0,0,0], target = 1
Output0
The only possible triplet has sum 0, which is closest to 1.

Constraints

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

Asked at 10 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate