Coding · stretch-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

3Sum Closest

mediumtwo-pointerssorting

Problem

Given an integer array nums and an integer target, pick three elements at distinct positions whose sum is as close as possible to target, and return that sum. Inputs are chosen so that a single sum is strictly closest.

  • nums has between 3 and 600 elements, each between -1000 and 1000.
  • target is an integer of magnitude at most 20,000, so it may lie outside the range of achievable sums.

Examples

  • nums = [3, -2, 5, -1, 7], target = 6 → 6. 3 + (-2) + 5 hits the target exactly, so nothing can be closer.
  • nums = [4, 4, 4], target = 9 → 12. Only one triple exists.
  • nums = [2, 2, 2, 1], target = -50 → 5. Every sum is far above the target; the smallest one, 1 + 2 + 2, is the closest.

Hints

  1. Fix one element. What does the remaining task look like, and have you solved something similar with a sorted array?
  2. With the rest sorted, two pointers can move toward the target: if the sum is below it, only moving the left pointer right can help; if above, only moving the right pointer left can.
  3. Sort, iterate the anchor, run the two-pointer sweep on the suffix, and keep the sum with the smallest absolute difference; stop immediately if the difference is zero.

Last reviewed 8 September 2026