3Sum Closest - Problem
Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input will have exactly one solution.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [-1,2,1,-4], target = 1
›
Output:
2
💡 Note:
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2)
Example 2 — Exact Match
$
Input:
nums = [0,0,0], target = 1
›
Output:
0
💡 Note:
The only possible sum is 0 + 0 + 0 = 0, which has distance |0-1| = 1 from target
Example 3 — Negative Target
$
Input:
nums = [1,1,1,0], target = -100
›
Output:
2
💡 Note:
Closest sum is 0 + 1 + 1 = 2, which is closest to target -100
Constraints
- 3 ≤ nums.length ≤ 500
- -1000 ≤ nums[i] ≤ 1000
- -104 ≤ target ≤ 104
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code