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
3Sum Closest Problem Overview-121-4nums = [-1, 2, 1, -4]target = 1Find three numbers whose sum is closest to target 1Possible sums: (-1+2+1)=2, (-1+2-4)=-3, (-1+1-4)=-4, (2+1-4)=-1Closest to 1: sum=2 (distance=1), sum=-1 (distance=2)Output: 2
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²)
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
68.0K Views
High Frequency
~25 min Avg. Time
2.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen