3Sum Closest – Solution & Complexity
Solution Walkthrough
Step 1: Start with the brute-force search space
- Any valid answer comes from choosing three different indices.
- The most direct solution is to try every triplet, compute its sum, and keep the one with the smallest absolute distance from
target. - This is easy to reason about and makes a good correctness baseline, but it checks
O(n^3)triplets.
Step 2: Brute-force triple loop
- Initialize
best_sumusing the first three values. - Enumerate every
i < j < kcombination, compute the current sum, and updatebest_sumwhenever the new sum is closer totarget. - Because the problem guarantees exactly one closest sum, a strict
<comparison is enough when updating the best answer.
- Initialize
Step 3: Sort first, then scan with two pointers
- After sorting, fix one value
nums[i]and search for the best pair in the suffixi + 1 .. n - 1. - With a sorted array, if the current triplet sum is too small, moving
leftright is the only way to increase it; if the sum is too large, movingrightleft decreases it. - This turns the inner
O(n^2)pair search into a linear two-pointer walk for each fixedi, reducing the total toO(n^2)after sorting.
- After sorting, fix one value
Step 4: Final optimal solution
Sort the array, initialize the best answer from the first triplet, then for each index run a two-pointer scan to keep improving the closest sum. Sorting costs
O(n log n), the scans costO(n^2), and the total isO(n^2)withO(1)extra space beyond the sort.