3Sum Closest - Problem

You're a treasure hunter exploring an ancient cave filled with numbered crystals. Your mission? Find the perfect combination of exactly three crystals whose combined power level gets as close as possible to your target magical energy!

Given an array nums of integers representing crystal power levels and a target energy value, find three crystals at different positions whose sum is closest to the target. Return the sum of these three crystals.

Example: With crystals [-1, 2, 1, -4] and target 1, the combination [-1 + 2 + 1 = 2] gets closest to our target of 1.

Note: Each input is guaranteed to have exactly one optimal solution - no ties!

Input & Output

example_1.py โ€” 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). The difference |2 - 1| = 1 is the smallest possible.
example_2.py โ€” All Positive
$ Input: nums = [1, 1, 1, 0], target = -100
โ€บ Output: 2
๐Ÿ’ก Note: The closest possible sum is 0 + 1 + 1 = 2. Even though target is -100, we must pick exactly 3 elements, so 2 is the closest we can get.
example_3.py โ€” Exact Match
$ Input: nums = [0, 0, 0], target = 1
โ€บ Output: 0
๐Ÿ’ก Note: The only possible sum is 0 + 0 + 0 = 0. The difference |0 - 1| = 1.

Visualization

Tap to expand
๐Ÿ”ฎ The Crystal Cave Method-4Crystal 1-1Crystal 21Crystal 32Crystal 4๐ŸŽฏ Target Energy: 1Two Hunters Searchโšก Magic Formula:1. Sort crystals by power2. Fix one crystal, use two hunters for the rest3. Hunters move smartly based on current total๐Ÿ†
Understanding the Visualization
1
Organize Crystals
First, arrange all crystals by their power level (sorting)
2
Pick First Crystal
Choose one crystal as your base
3
Smart Search
Use two treasure hunters from opposite ends to find the best pair
4
Adjust Strategy
If total power is too low, get stronger crystal. If too high, get weaker one
Key Takeaway
๐ŸŽฏ Key Insight: Sorting enables the two-pointer technique - when sum is too small, we know we need a larger number (move left pointer right), when too large, we need a smaller number (move right pointer left). This eliminates the need to check all combinations!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยณ)

Three nested loops each running up to n times

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track the closest sum

n
2n
โœ“ Linear Space

Constraints

  • 3 โ‰ค nums.length โ‰ค 1000
  • -1000 โ‰ค nums[i] โ‰ค 1000
  • -104 โ‰ค target โ‰ค 104
  • Guaranteed to have exactly one solution
Asked in
Amazon 45 Google 38 Meta 32 Microsoft 28 Apple 22
89.5K Views
High Frequency
~18 min Avg. Time
2.8K 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