Magicsheet logo

3Sum Closest

Medium
40.3%
Updated 6/1/2025

3Sum Closest

What is this problem about?

In the 3Sum Closest coding problem, you are given an array of integers and a target value. Your goal is to find three integers in the array such that their sum is as close to the target as possible. Unlike the standard 3Sum, you aren't looking for zero; you are looking for the minimum absolute difference between the sum and the target. You only need to return the sum of these three integers.

Why is this asked in interviews?

Companies like Apple and Bloomberg use the 3Sum Closest interview question to see how candidates adapt the two-pointer strategy. It requires maintaining a "global minimum" variable and constantly updating it, which tests attention to detail and logic under the pressure of a shifting target.

Algorithmic pattern used

Similar to its predecessor, this problem relies on the Sorting and Two Pointers interview pattern. Sorting allows you to decide whether to move your left pointer (to increase the sum) or your right pointer (to decrease the sum) to get closer to the target.

Example explanation

Input: nums = [-1, 2, 1, -4], target = 1.

  1. Sort: [-4, -1, 1, 2].
  2. **Fix -4**: Pointers at -1 and 2. Sum = -3. Distance from target 1 is 4.
  3. **Fix -1**: Pointers at 1 and 2. Sum = 2. Distance from target 1 is 1. Since 2 is the closest sum we've found so far, and no other combination gets closer, the answer is 2.

Common mistakes candidates make

  • Incorrect Initialization: Setting the initial "closest sum" to 0. If the target is 1000, 0 might be interpreted as "close" when it isn't. Better to use the sum of the first three elements.
  • Stopping Early: Assuming that finding a sum "close" to the target is enough without checking if an even closer sum exists elsewhere in the array.
  • Handling the Absolute Difference: Forgetting that "closeness" is measured by sumtarget|sum - target|, but the return value is the sumsum itself.

Interview preparation tip

Practice verbalizing how you update the "best" result. In many "closest" or "maximum" problems, the logic for updating the result is just as important as the traversal itself.

Similar Questions