Find three elements whose sum is closest to X
Filed under Flipkart
Free read 3 of 3Confirm what should be returned (the sum itself or the triplet) and how to handle multiple triplets yielding the same closest sum.
The question
Given an array of N elements and an integer X, find three elements in the array whose sum is closest to X.
Constraints
- N is at least 3.
- Elements can be positive, negative, or zero.
Examples
- Input
- nums = [-1, 2, 1, -4], X = 1
- Output
- 2
- Why
- The sum that is closest to 1 is (-1 + 2 + 1 = 2).
Approach
Confirm what should be returned (the sum itself or the triplet) and how to handle multiple triplets yielding the same closest sum.
Check every possible triplet using three nested loops, resulting in O(N^3) time complexity.
Sort the array. Iterate through each element as the first of the triplet, then use two pointers (left and right) for the remaining portion to find the closest sum in O(N^2) time.
Array with exactly 3 elements, and arrays with duplicate values.
Solution
O(N^2) time, O(1) space
def threeSumClosest(nums: list[int], target: int) -> int:
nums.sort()
closest_sum = sum(nums[:3])
for i in range(len(nums) - 2):
left, right = i + 1, len(nums) - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum
if current_sum < target:
left += 1
elif current_sum > target:
right -= 1
else:
return current_sum
return closest_sum
Tips
- What they are testing: Test with arrays having exact matches, multiple triplets with the same closest sum, and small arrays.
- Common mistake: Forgetting to sort the array first, which prevents the efficient use of the two-pointer technique.
Follow-ups
- Discussed edge cases like empty/null array, array with less than 3 numbers, no such triplet, and multiple valid triplets (interviewer confirmed printing any one)
Related Flipkart questions
Collected from public candidate posts and coding forums. Updated Nov 2026.