16. 3Sum Closest
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find three integers in a given array nums whose sum is closest to a specified target value. We need to return this sum. The input guarantees that there will be exactly one solution.
Solution
3Sum Closest in Python
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
# Sort the array to use the two-pointer technique.
nums.sort()
n = len(nums)
min_diff = float('inf')
closest_sum = 0
# Iterate through the array to fix the first element of the triplet.
for i in range(n - 2):
# Optimization: skip duplicate elements for the first number.
# This avoids redundant computations.
if i > 0 and nums[i] == nums[i-1]:
continue
# Use two pointers for the remaining part of the array.
left, right = i + 1, n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
# Check if the current sum is closer to the target.
if abs(current_sum - target) < min_diff:
min_diff = abs(current_sum - target)
closest_sum = current_sum
# Move pointers based on the comparison with the target.
if current_sum < target:
left += 1
elif current_sum > target:
right -= 1
else:
# If the sum is exactly the target, the difference is 0.
# This is the minimum possible difference, so we can return immediately.
return target
return closest_sum
3Sum Closest in Java
class Solution {
public int threeSumClosest(int[] nums, int target) {
// Sort the array to use the two-pointer technique.
Arrays.sort(nums);
int n = nums.length;
int minDiff = Integer.MAX_VALUE;
int closestSum = 0;
// Iterate through the array to fix the first element of the triplet.
for (int i = 0; i < n - 2; i++) {
// Optimization: skip duplicate elements for the first number.
// This avoids redundant computations.
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// Use two pointers for the remaining part of the array.
int left = i + 1;
int right = n - 1;
while (left < right) {
int currentSum = nums[i] + nums[left] + nums[right];
// Check if the current sum is closer to the target.
if (Math.abs(currentSum - target) < minDiff) {
minDiff = Math.abs(currentSum - target);
closestSum = currentSum;
}
// Move pointers based on the comparison with the target.
if (currentSum < target) {
left++;
} else if (currentSum > target) {
right--;
} else {
// If the sum is exactly the target, the difference is 0.
// This is the minimum possible difference, so we can return immediately.
return target;
}
}
}
return closestSum;
}
}
3Sum Closest in C++
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
// Sort the array to use the two-pointer technique.
sort(nums.begin(), nums.end());
int n = nums.size();
int minDiff = INT_MAX;
int closestSum = 0;
// Iterate through the array to fix the first element of the triplet.
for (int i = 0; i < n - 2; ++i) {
// Optimization: skip duplicate elements for the first number.
// This avoids redundant computations.
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
// Use two pointers for the remaining part of the array.
int left = i + 1;
int right = n - 1;
while (left < right) {
int currentSum = nums[i] + nums[left] + nums[right];
// Check if the current sum is closer to the target.
if (abs(currentSum - target) < minDiff) {
minDiff = abs(currentSum - target);
closestSum = currentSum;
}
// Move pointers based on the comparison with the target.
if (currentSum < target) {
left++;
} else if (currentSum > target) {
right--;
} else {
// If the sum is exactly the target, the difference is 0.
// This is the minimum possible difference, so we can return immediately.
return target;
}
}
}
return closestSum;
}
};
3Sum Closest in TypeScript
function threeSumClosest(nums: number[], target: number): number {
// Sort the array to use the two-pointer technique.
nums.sort((a, b) => a - b);
const n = nums.length;
let minDiff = Infinity;
let closestSum = 0;
// Iterate through the array to fix the first element of the triplet.
for (let i = 0; i < n - 2; i++) {
// Optimization: skip duplicate elements for the first number.
// This avoids redundant computations.
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}
// Use two pointers for the remaining part of the array.
let left = i + 1;
let right = n - 1;
while (left < right) {
const currentSum = nums[i] + nums[left] + nums[right];
// Check if the current sum is closer to the target.
if (Math.abs(currentSum - target) < minDiff) {
minDiff = Math.abs(currentSum - target);
closestSum = currentSum;
}
// Move pointers based on the comparison with the target.
if (currentSum < target) {
left++;
} else if (currentSum > target) {
right--;
} else {
// If the sum is exactly the target, the difference is 0.
// This is the minimum possible difference, so we can return immediately.
return target;
}
}
}
return closestSum;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.