MediumTwo Pointers

3Sum Closest

Explanation & Solution

Description

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Input:nums = [-1, 2, 1, -4], target = 1
0
-1
1
2
2
1
3
-4

Output: 2

Explanation: The sum that is closest to the target is 2, which comes from (-1 + 2 + 1 = 2).

Constraints

  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -10⁴ <= target <= 10⁴

Approach

Two Pointers pattern

1. Sort the Array

  • Sort nums in ascending order
  • This enables the two-pointer technique by creating a predictable order

2. Initialize Closest Sum

  • Set closest to the sum of the first three elements
  • This gives us a valid starting comparison value

3. Iterate with a Fixed Pointer

  • Loop index i from 0 to nums.length - 3
  • For each i, the element nums[i] is fixed as the first of three numbers

4. Set Up Two Pointers

  • Place left at i + 1
  • Place right at the last index of the array
  • These two pointers will scan inward to find the best pair

5. Compute the Three-Element Sum

  • Calculate sum = nums[i] + nums[left] + nums[right]
  • Compare |sum - target| with |closest - target|
  • If the current sum is closer, update closest

6. Move Pointers Based on Comparison

  • If sum < target: increment left to increase the sum
  • If sum > target: decrement right to decrease the sum
  • If sum === target: return immediately — exact match is the closest possible

7. Return the Result

  • After all iterations, return closest
  • This holds the three-element sum nearest to the target

Key Insight

Sorting the array transforms a brute-force O(n³) problem into an O(n²) solution. By fixing one element and using two pointers that move inward, we efficiently explore all meaningful triplet combinations without redundant checks.

Visualization

Input:
[-1, 2, 1, -4], target = 1
-102112-43

Press ▶ or use ← → to step through

Left (L)Right (R)ConvergedDone
6 steps

Solution Code