3sum-closest.sh — zsh
arraystwo-pointerssorting

Given an integer array nums of length at least 3 and an integer target, choose three distinct indices i, j, and k and return the sum nums[i] + nums[j] + nums[k] whose value is closest to target.

You only need to return the closest sum, not the actual triplet.

Input / output

  • Input: nums: int[], target: int
  • Output: int

Examples

  1. nums = [-1, 2, 1, -4], target = 1 returns 2 because (-1 + 2 + 1) = 2, which is closest to 1.
  2. nums = [0, 0, 0], target = 1 returns 0.
  3. nums = [1, 2, 4], target = 8 returns 7 because that is the only possible triplet sum.

Constraints

  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -10^4 <= target <= 10^4
  • Exactly one sum is closest to target in the test data, so no tie-breaking rule is needed between two different sums.

Follow-up Can you improve the brute-force O(n^3) search by sorting the array first and then using a two-pointer scan for each fixed first value?

Examples
Example 1
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Example 2 (all zeros)
Input: nums = [0,0,0], target = 1
Output: 0