12 · Two Pointers

#16 3Sum Closest

Mediumsolve on LeetCode ↗

frequently reported atBloombergAmazonGoogleMeta

the problem

In plain words

Pick three numbers from nums, at three different positions, whose sum is as close as possible to target. Return that sum. Exactly one closest sum exists.

in nums = [-1,2,1,-4], target = 1

out 2

-1 + 2 + 1 = 2 is at distance 1; no triple gets closer.

in nums = [0,0,0], target = 1

out 0

  • 3 ≤ n ≤ 500
  • -1000 ≤ nums[i] ≤ 1000
  • -10⁴ ≤ target ≤ 10⁴

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #15
      3Sum
      Mediumin Two Pointers
    2. #167