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.
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.
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.
Input: nums = [-1, 2, 1, -4], target = 1.
[-4, -1, 1, 2].-4**: Pointers at -1 and 2. Sum = -3. Distance from target 1 is 4.-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.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.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| 4Sum | Medium | Solve | |
| Meeting Scheduler | Medium | Solve | |
| Sort Colors | Medium | Solve | |
| 3Sum | Medium | Solve | |
| The k Strongest Values in an Array | Medium | Solve |