You get an array of whole numbers, nums, and a number target. Pick three numbers from three different positions in the array and add them up.
Return the sum that lands nearest to target. Only the sum is returned, not the positions. The inputs are chosen so that just one sum is the closest.
Example 1
Input: nums = [4, -3, 1, 7, 0], target = 6 Output: 5 Why: -3 + 1 + 7 = 5; no triple adds up to 6 or 7
2 more examples and the constraints
Example 2
Input: nums = [2, 2, 2], target = 1 Output: 6 Why: there is only one triple, so its sum wins
Example 3
Input: nums = [-5, 2, 8, -1, 3], target = 4 Output: 4 Why: -1 + 2 + 3 hits the target exactly
Constraints
- 3 ≤ length of nums ≤ 500
- −1,000 ≤ nums[i] ≤ 1,000
- −10,000 ≤ target ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every tripleO(n³)
- Sort + two pointersO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 500 numbers | Verdict |
|---|---|---|---|
| Try every triple | O(n³) | Correct, but far too much work | |
| Sort + two pointers | O(n²) | Best; one walk per fixed number |
n = length of nums.
Edge cases to test
- Exactly three numbers. [2, 2, 2] has one triple; its sum is the answer, however far from the target.
- An exact hit. Return it right away: nothing can be closer than distance 0.
- Target outside every sum. With [1, 2, 3, 4] and target 10,000 the answer is 9, the three largest.
- Repeated values. [0, 0, 0, 0] still gives 0; repeats need no special handling here.
Common mistakes
- Starting
bestat a huge number and then computingbest − target, which can overflow or be returned if nothing replaces it. - Comparing the sums themselves instead of their distance to the target.
- Moving both pointers after every sum, which skips triples that could be the answer.
How to talk through it
- 1Clarify. Is there always one closest sum? Do I return the sum or the positions? May I sort the input?
- 2Give the brute force. Three loops, keep the nearest sum: O(n³), about 20 million triples for 500 numbers.
- 3Reduce to two numbers. Fix one number; the other two come from a sorted range, where two pointers know which way to move.
- 4Code the walk. Update
beston every sum, then moveLorRby comparing with the target. Return early on an exact hit. - 5Test out loud. Run the three-number case and a target far above every sum before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?