3Sum Closest LeetCode
Key takeaways:
The problem asks to find three integers in an array whose sum is closest to a given target.
The input is an array of integers and a target value.
The task is to return the sum of three integers that is closest to the target.
Sorting the array simplifies finding the closest sum.
Two pointers are used after fixing one element to find the other two elements that sum closest to the target.
Time complexity is
for sorting, with an additional for the two-pointer approach.
The 3Sum Closest problem involves finding the triplet of integers in an array whose sum is closest to a given target value. This problem is significant because it helps in scenarios where we need to approximate a desired sum with minimal deviation. For instance, in financial forecasting, identifying the closest sum can aid in making accurate predictions.
Consider an example where we have an array [-1, 2, 1, -4, 5] and a target value of 1. By finding the triplet with the closest sum to 1 (e.g., -1 + 1 + 2 = 2), we can visualize this sum in the following illustration:
Problem statement
Find three integers in a given integer array numbers of length n and an integer target, such that their sum is closest to the target value.
Return the sum of the three integers that are closest to the target.
Assume that each input array numbers has exactly one solution.
Explanation
The task is to find three numbers in a given list of integers (array) so that their sum is as close as possible to a specified target value. The goal is to return the sum of those three numbers. It’s assumed that there is exactly one solution for each input list.
Expected Input:
A list of integers
numbers, which represents the input array.An integer
target, indicating the target value.
Expected Output:
An integer representing the sum of three integers in the array
numbersthat is closest to the target valuetarget.
Examples
Let’s discuss some examples to understand the concept of three sum closest:
Example 1:
Input: numbers = [-1,2,1,-4], target = 1Output: 2Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Example 2:
Input: numbers = [0,0,0], target = 1Output: 0Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
Knowledge test
Test the user’s understanding of the concepts discussed so far with any widget in the exercise block of the Answer editor.
Consider an input array nums = [-2, 0, 1, 2] and a target value target = 0. What is the output of the threeSumClosest function for this input?
-1
0
1
2
Algorithm to solve 3Sum Closest problem
Suppose we have an array numbers = [10, -20, 15, 25] and a target value target = 5. We need to find three integers in the array such that their sum is closest to the target value.
Sort the array: After sorting, the array becomes
[-20, 10, 15, 25].Initialize
res: Initializeresto the sum of the first three numbers:-20 + 10 + 15 = 5.Iterate through the array: Start iterating through the array elements.
For
i = 0:Initialize pointers
start = 1andend = 3.While loop:
Calculate
current_sum = -20 + 10 + 25 = 15.Adjust pointers: Decrement
end.Calculate
current_sumagain:-20 + 10 + 15 = 5.Update
restocurrent_sum.
For
i = 1:Initialize pointers
start = 2andend = 3.While loop:
Calculate
current_sum = 10 + 15 + 25 = 50.Adjust pointers: Decrement
end.Calculate
current_sumagain:10 + 15 + 15 = 40.No update to
res.
For
i = 2:Initialize pointers
start = 3andend = 3.While loop:
Calculate
current_sum = 15 + 25 + 25 = 65.Adjust pointers: Decrement
end.No update to
res.
Return
res: The function returns5, as it represents the closest sum to the target.The closest sum of three integers in the array
numbersto the target value5is5.
Code
We already discussed the process and algorithm to solve the problem. Now, let’s code it!
def threeSumClosest(nums, target):nums.sort()res = sum(nums[:3])for i in range(len(nums) - 2):start = i + 1end = len(nums) - 1while start < end:current_sum = nums[i] + nums[start] + nums[end]if current_sum > target:end -= 1else:start += 1if abs(current_sum - target) < abs(res - target):res = current_sumreturn res# Example usage:numbers = [10, -20, 15, 25]target = 5result = threeSumClosest(numbers, target)print("Closest sum of three integers:", result)
Educative 99 helps you solve complex coding problems by teaching you to recognize patterns and apply the right algorithms.
Explanation
Here’s a detailed explanation of the code:
Line 2: We sort the input array
numsin ascending order to simplify the process of finding the closest sum.Line 3: We initialize the variable
resto the sum of the first three numbers in the sorted array. This provides an initial approximation for the closest sum.Line 4-7: We iterate through the array elements using a loop. For each element
nums[i], initialize two pointersstartandendto find the remaining two numbers in the triplet.Line 9–15: Inside the nested while loop, we calculate the sum of the current triplet (
current_sum = nums[i] + nums[start] + nums[end]). Adjust the pointersstartandendbased on the comparison ofcurrent_sumwith the target value. Updateresif the absolute difference betweencurrent_sumand the target is less than the absolute difference betweenresand the target.Line 16: After iterating through all possible triplets, we return the closest sum found stored in the variable
res.Line 20–22: We define the example input array
numbersand target valuetarget. Then call thethreeSumClosestfunction with the provided input array and target value, and print the result, which is the closest sum of three integers in the array to the target value.
Time complexity
Sorting the input array takes
time, where is the length of the input array. The main loop iterates through each element of the array once, and for each element, it performs a two-pointer approach that takes
time in the worst case. Within the loop, the two-pointer approach moves the
startandendpointers toward each other until they meet, which takestime in the worst case. Overall, the time complexity is dominated by the sorting step and the main loop, resulting in
time complexity.
Space complexity
The space complexity is primarily determined by the space used for storing the sorted array, which requires
additional space. Other variables, such as
res,start,end, andcurrent_sumrequire constant space, regardless of the size of the input array.Therefore, the space complexity is
due to the sorted array.
Free Resources