3Sum Closest

Medium Two Pointers

Problem

Given an integer array nums and an integer target, return the sum of three integers in nums such that the sum is closest to target. You may assume that each input would have exactly one solution.

  • 3 ≤ nums.length ≤ 10³
  • −10³ ≤ nums[i] ≤ 10³
  • −10⁴ ≤ target ≤ 10⁴

Example

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

Sorting the array results in [-4, -1, 1, 2]. Starting with the first element -4, the two-pointer approach checks pairs (left=1, right=2) to find sums closest to 1. The sum (-4 + 1 + 2 = -1) is 2 away from target. Moving pointers and iterating through the array, the closest sum found is 2 (-1 + 1 + 2), which is only 1 away from target. The algorithm returns 2 as the closest sum.

Approach

Straightforward Solution

A brute-force approach would check all triplets (O(n^3)) and track the closest sum, which is inefficient for large inputs.

Core Observation

The problem requires finding three numbers whose sum is closest to a target. Sorting the array enables a two-pointer approach to efficiently explore pairs for each fixed element, reducing the search space from O(n^3) to O(n^2).

Path to Optimal

Sorting the array allows fixing one element and using two pointers to scan the remaining elements for the best pair complement. This reduces complexity to O(n^2). The two-pointer technique exploits the sorted order to move pointers inward based on the comparison of the current sum to the target, efficiently narrowing down the closest sum.

Optimal Approach

Sort the array. For each element, use two pointers starting just after the fixed element and at the end of the array. Calculate the sum of the three elements. If the sum equals the target, return immediately. Otherwise, update the closest sum if the current sum is nearer to the target. Move the left pointer right if the sum is less than the target, or the right pointer left if the sum is greater. Continue until pointers meet. Return the closest sum found.

Time

O(n^2)

Sorting takes O(n log n). The main loop runs O(n) times, and for each iteration, the two-pointer scan runs in O(n), resulting in O(n^2) overall.

Space

O(1)

The algorithm sorts the input in place and uses only a fixed number of variables, requiring constant auxiliary space.

Pattern Spotlight

Two Pointers (Sorted Array Pair Search)

When searching for pairs or triplets with a sum condition in a sorted array, fix one element and use two pointers moving inward to efficiently find the best complement, eliminating the need for nested loops and reducing complexity from O(n^3) to O(n^2).

Solution

1class Solution:
2 def threeSumClosest(self, nums: list[int], target: int) -> int:
3 nums.sort()
4
5 closest = nums[0] + nums[1] + nums[2]
6
7 for i in range(len(nums) - 2):
8 left = i + 1
9 right = len(nums) - 1
10
11 while left < right:
12 total = nums[i] + nums[left] + nums[right]
13
14 if abs(total - target) < abs(closest - target):
15 closest = total
16
17 if total < target:
18 left += 1
19 elif total > target:
20 right -= 1
21 else:
22 return target
23
24 return closest

Step-by-Step Solution

1

Sort the Array and Initialize Closest Sum

3nums.sort()
5closest = nums[0] + nums[1] + nums[2]

Objective

To prepare the input for efficient two-pointer scanning by sorting and to initialize the closest sum with the first triplet.

Key Insight

Sorting the array is essential to apply the two-pointer technique. Initializing the closest sum with the first three elements provides a baseline for comparison, ensuring the algorithm always has a valid candidate to update.

Interview Quick-Check

Core Logic

Sorting enables the two-pointer approach by ordering elements, which allows pointer movements to predictably increase or decrease the sum.

State & Boundaries

Initializing closest with the sum of the first three elements ensures a valid starting point for comparison.

Common Pitfalls & Bugs

Failing to sort the array breaks the two-pointer logic, as pointer movements would not reliably adjust the sum towards the target.

2

Iterate Through Array Fixing One Element and Use Two Pointers to Find Closest Sum

7for i in range(len(nums) - 2):
8 left = i + 1
9 right = len(nums) - 1
11 while left < right:
12 total = nums[i] + nums[left] + nums[right]
14 if abs(total - target) < abs(closest - target):
15 closest = total
17 if total < target:
18 left += 1
19 elif total > target:
20 right -= 1
21 else:
22 return target

Objective

To explore all triplets by fixing one element and using two pointers to find the pair that yields the sum closest to the target.

Key Insight

Fixing one element and scanning the rest with two pointers leverages the sorted order to efficiently adjust the sum towards the target. Updating the closest sum only when a better candidate is found ensures the algorithm converges on the optimal solution. Immediate return upon exact match optimizes performance.

Interview Quick-Check

Core Logic

For each fixed element, the two-pointer approach moves pointers inward based on whether the current sum is less or greater than the target, efficiently narrowing the search space.

State & Boundaries

The while loop continues as long as left < right, ensuring all pairs for the fixed element are considered without repetition.

Common Pitfalls & Bugs

Not updating the closest sum correctly or failing to return immediately when the exact target sum is found can lead to incorrect or inefficient solutions.

Complexity

This approach reduces the time complexity from O(n^3) to O(n^2) by avoiding redundant checks and leveraging sorted order.

3

Return the Closest Sum Found

24return closest

Objective

To output the sum of three integers closest to the target after exploring all valid triplets.

Key Insight

After exhaustive yet efficient exploration, the closest sum variable holds the best candidate. Returning it finalizes the solution.

Interview Quick-Check

Core Logic

Returning the closest sum after all iterations ensures the algorithm outputs the optimal solution found.

Line Analysis

This solution has 5 Critical lines interviewers watch for.

Line 21 Critical
else:

If the current sum equals the target, return the target immediately.

An exact match is the closest possible sum, so the algorithm can terminate early for optimal efficiency.

Line 22 Critical
return target

Return the target immediately upon exact match.

Immediate return avoids unnecessary computation once the optimal solution is found, improving performance.

Line 3 Critical
nums.sort()

Sort the input array in ascending order.

Sorting is critical because it enables the two-pointer technique by ensuring that moving pointers inward predictably increases or decreases the sum, allowing efficient search.

Line 14 Critical
if abs(total - target) < abs(closest - target):

Check if the current sum is closer to the target than the previously recorded closest sum.

This comparison identifies whether the current triplet provides a better approximation to the target, guiding updates to the closest sum.

Line 15 Critical
closest = total

Update the closest sum with the current sum if it is closer to the target.

Updating the closest sum ensures the algorithm retains the best candidate found so far, which is critical for correctness.

Line 5 Core
closest = nums[0] + nums[1] + nums[2]

Initialize the closest sum with the sum of the first three elements.

This provides a valid baseline for comparison, ensuring the algorithm always has a candidate sum to update when a closer sum is found.

Line 12 Core
total = nums[i] + nums[left] + nums[right]

Calculate the sum of the fixed element and the elements at left and right pointers.

Computing the current triplet sum is essential to compare against the target and decide pointer movements or updates.

Line 17 Core
if total < target:

If the current sum is less than the target, move the left pointer right to increase the sum.

Because the array is sorted, moving the left pointer right increases the sum, potentially bringing it closer to the target.

Line 19 Core
elif total > target:

If the current sum is greater than the target, move the right pointer left to decrease the sum.

Moving the right pointer left decreases the sum, potentially bringing it closer to the target due to the sorted order.

Line 24 Core
return closest

Return the closest sum found after exploring all triplets.

After exhaustive search, the closest sum variable holds the best approximation to the target, which is the correct output.

Line 7 Core
for i in range(len(nums) - 2):

Iterate through the array, fixing one element at a time for the triplet.

Fixing one element reduces the problem to finding a pair whose sum complements the fixed element to approach the target, enabling the two-pointer approach.

Line 11 Core
while left < right:

Loop while the left pointer is less than the right pointer.

This condition ensures all pairs between left and right pointers are considered without overlap or repetition.

Line 8 Standard
left = i + 1

Initialize the left pointer just after the fixed element.

Starting the left pointer immediately after the fixed element ensures unique triplets without repetition and maintains sorted order for pointer movement.

Line 9 Standard
right = len(nums) - 1

Initialize the right pointer at the end of the array.

The right pointer starts at the far end to maximize the initial sum range and allows contraction towards the target.

Line 18 Standard
left += 1

Increment the left pointer.

Advancing the left pointer explores larger values to increase the sum towards the target.

Line 20 Standard
right -= 1

Decrement the right pointer.

Moving the right pointer inward explores smaller values to reduce the sum towards the target.

Test Your Understanding

Why does moving the pointer at the smaller or larger value help find a sum closer to the target?

Because the array is sorted, increasing the smaller pointer increases the sum, and decreasing the larger pointer decreases the sum, allowing the algorithm to move towards the target sum efficiently.

Related Problems

Two Pointers pattern

Don't just read it. Drill it.

Reconstruct 3Sum Closest from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the 3Sum Closest drill

or drill a free problem