Algorithm Day110 - 3Sum Closest
LC-16 3Sum Closest
π Problem
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.
π¬ Examples
Example 1
1 | Input: nums = [-1,2,1,-4], target = 1 |
π‘ Intuition
The problem is similar to the classic 3Sum, but instead of finding an exact match, we want the closest sum.
We can sort the array first, then use a two-pointer approach to efficiently explore possible triplets.
π’ Java Code (Sorting + Two Pointers)
1 | import java.util.*; |
β± Complexity Analysis
- Time: O(nΒ²) β Sorting takes O(n log n), and two-pointer scanning for each element takes O(nΒ²).
- Space: O(1) β In-place sorting, no extra space used.
βοΈ Summary
- Sort the array to apply two-pointer logic.
- Track the closest sum as we move pointers.
- Efficient and intuitive extension of the 3Sum problem.