3Sum Closest

Given an integer array `nums` of length `n` and an integer `target`, find three integers at distinct indices in `nums` whose sum is closest to `target`. Return that sum. You may assume each input has exactly one closest sum.

30:00

3Sum Closest
medium
Free written solution
Topics
Companies

Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums whose sum is closest to target. Return that sum. You may assume each input has exactly one closest sum.

Example 1:
Input: {"nums":[-1,2,1,-4],"target":1}
Output: 2
Constraints:
  • 3≤nums.length≤5003 \leq \text{nums.length} \leq 500

  • −1000≤nums[i]≤1000-1000 \leq \text{nums}[i] \leq 1000

  • −104≤target≤104-10^4 \leq \text{target} \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[-1,2,1,-4],"target":1}

Sort the array: [-4, -1, 1, 2]. Sorted order lets two pointers steer the sum up or down.

sorted nums

-4

0

-1

1

1

2

2

3

smallerbiggertarget 1

target

1

this sum

-

best

-

Variables
VariableValue
target1
DepthFunction Call
Stack empty
0/7