Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Two pointers

The triple sum closest to a target

Medium · Target 20 minutes · Two pointers

Given an integer array nums of length at least 3 and an integer target, choose three elements at different indices whose sum is as close to target as possible, and return that sum. If two sums are equally close, return the smaller.

Examples

InputOutputWhy
nums = [-1, 2, 1, -4], target = 12−1 + 2 + 1 = 2, at distance 1.
nums = [0, 2, 4, 6], target = 980 + 2 + 6 = 8 and 0 + 4 + 6 = 10 are both 1 away; 8 is smaller.

Constraints

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

Hints

Hint 1

Trying every triple is O(n³). Sort first: what does the order let you do once one element is fixed?

Hint 2

With nums[i] fixed, you want a pair from the rest whose sum is as close as possible to target − nums[i]. That is the sorted two-sum walk.

Hint 3

Move the left pointer right when the sum is too small and the right pointer left when it is too big, checking every sum you see against the best so far.

Where people lose marks

  • Initialising the best sum with a huge constant and then comparing distances in a 32-bit type where the subtraction overflows. Start from the first triple instead.
  • Ignoring the tie rule: with sums 8 and 10 around a target of 9, returning whichever was seen first.
  • Moving both pointers at once, which skips pairs.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.