Problem 338406 · medium · Phase 03 Linear Management & Searching

Closest Triple Sum

two pointers · sorting · k-sum

Given a list of integers nums with at least three elements and an integer target, choose three distinct indices whose values sum as close as possible to target, and return that sum. If two different sums are equally close, return the smaller one.

Examples

Input:  nums = [-1, 2, 1, -4], target = 1
Output: 2
Explanation: -1 + 2 + 1 = 2 is one away from 1.

Input:  nums = [1, 1, 1, 0], target = 100
Output: 3

Constraints

  • 3 <= len(nums) <= 3000, -10**4 <= nums[i] <= 10**4
  • Target: O(n^2) time after sorting, O(1) extra space.

Goals

  • Fix one element and run a converging two-pointer scan on the rest
  • Track the closest sum with a deterministic tie-break
Starting Python…