3sum Closest
Algorithm/TwoPointers
Intuition
The goal is to find a triplet in nums
whose sum is closest to a given target
. We can leverage a similar two-pointer approach as in the "3Sum" problem, but instead of looking for a sum of exactly zero, we aim to find the sum closest to the target
.
Approach
Below is the step-by-step breakdown of the approach:
- Sort the Array:
- First, sort
nums
in ascending order, which allows us to use two pointers effectively for summing values.
- First, sort
- Initialize Closest Sum:
- Set
ans
as the sum of the first three numbers, as an initial closest sum. - Calculate the initial difference,
diff
, betweenans
andtarget
.
- Set
- Iterate with Fixed Pointer:
- For each index
left
, treatnums[left]
as the first number of the triplet.
- For each index
- Two-Pointer Technique:
- Set
middle
toleft + 1
andright
tonums.length - 1
. - Calculate
sum = nums[left] + nums[middle] + nums[right]
. - If
sum
equalstarget
, returnsum
, as it's the closest possible. - Otherwise, calculate the difference,
tempDiff
, betweensum
andtarget
.- If
tempDiff
is smaller thandiff
, updateans
withsum
anddiff
withtempDiff
. - If
sum
is greater thantarget
, moveright
to decrease the sum. - If
sum
is less thantarget
, movemiddle
to increase the sum.
- If
- Set
- Return the Result:
- After finding the closest sum in all iterations, return
ans
.
Complexity
- Time complexity: , sorting takes O(n log n), and the two-pointer traversal for each element takes O(n), making it O(n²) overall.
- Space complexity: for extra space (excluding the result variable).