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
Understanding the Visualization
1
Input
Array of integers and target value
2
Process
Find three numbers whose sum is closest to target
3
Output
Return the actual sum (not indices)
Key Takeaway
🎯 Key Insight: Sort first to enable efficient two-pointer search, reducing from O(n³) to O(n²)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code