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 - Visual Guide INPUT Array nums: -1 i=0 2 i=1 1 i=2 -4 i=3 Target: 1 After Sorting: -4 -1 1 2 Find 3 nums with sum closest to target ALGORITHM STEPS 1 Sort Array Enable two-pointer technique 2 Fix First Element Loop i from 0 to n-2 3 Two Pointers left=i+1, right=n-1 4 Update Closest Track min difference Two Pointer Example: -4 i -1 L 1 2 R Time: O(n^2) | Space: O(1) (or O(n) for sorting) FINAL RESULT Closest Triplet Found: -1 + 2 + 1 = 2 Sum = 2 Target = 1 Difference = |2-1| = 1 OK Closest possible sum Key Insight: Sorting enables the two-pointer technique: if current sum is less than target, move left pointer right to increase sum; if greater, move right pointer left to decrease sum. This reduces O(n^3) to O(n^2). TutorialsPoint - 3Sum Closest | Optimal Two-Pointer Solution
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