Finding three elements in an array whose sum is closest to a given number
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Arrays are a fundamental data structure in programming, widely used in various applications across multiple domains. A common computational problem involving arrays is finding three elements whose sum is closest to a given target number. This problem has a blend of theoretical and practical significance, allowing us to understand optimization techniques better. In this article, we delve into the problem's intricacies, explore solutions, and illustrate with examples. Let's dive in.
Problem Definition
We are given an array arr of integers and a target integer target. The task is to find three integers in the array such that the sum of these three integers is closest to target. We return the sum of the three integers. You may assume that each input would have exactly one solution.
Approach
To efficiently solve this problem, a sorted array approach along with the two-pointer technique is often employed. Here's a step-by-step explanation:
- Sort the Array: The solution begins by sorting the input array. Sorting helps in efficiently finding the required sum using a two-pointer strategy.
- Initialize Variables: We need a variable to keep track of the closest sum we encounter as we iterate through the array. Initialize
closestSumwith the sum of the first three numbers as a starting point. - Iterate and Compare: For each element
arr[i]in the array:- Set two pointers: one right after the current element (
left), and the other at the end of the array (right). - Calculate the sum of the three elements:
arr[i] + arr[left] + arr[right]. - If the calculated sum exactly equals the target, it's the closest possible, and we return it.
- Update
closestSumif the calculated sum is closer to the target than the previousclosestSum.
- Adjust Pointers:
- If the sum is less than the target, increment the
leftpointer to increase the sum. - If the sum is greater than the target, decrement the
rightpointer to decrease the sum.
- Continue Until Completion:
- Repeat until all possible combinations of three elements are assessed.
- Return the
closestSumafter exiting the loop.
Example
Let's take an example array and a target to illustrate the approach.
Step-by-Step Solution:
- Sort the array:
[-4, -1, 1, 2] - Initialize
closestSumto the first three numbers:-4 + (-1) + 1 = -4 - Iterate over each element:
- For
i = 0, arr[i] = -4:left = 1, arr[left] = -1right = 3, arr[right] = 2- Calculate
currSum = -4 + (-1) + 2 = -3 - Update
closestSumto-3since|-3 - 1| < |-4 - 1| currSum < target, incrementleft
- For
i = 1, arr[i] = -1:left = 2, arr[left] = 1right = 3, arr[right] = 2- Calculate
currSum = -1 + 1 + 2 = 2 - Update
closestSumto2since|2 - 1| < |-3 - 1| currSum > target, decrementright
After iterating through each element, the closest sum calculated is 2.
Complexity
- Time Complexity: Sorting the array takes and iterating through the elements with the two-pointer approach results in a time complexity of . Thus, the total time complexity is .
- Space Complexity: The space complexity is if we don't consider the input array as additional space.
Key Points Summary
| Aspect | Details |
| Problem Type | Optimization, Array Traversal |
| Efficient Approach | Sorting + Two-pointer Technique |
| Time Complexity | (Due to double iteration) |
| Space Complexity | (Ignoring input array storage) |
| Assumptions | Exactly one solution always exists |
Subtopics
Edge Cases
- Minimum Length: The problem is undefined for arrays of length less than three.
- Identical Elements: The sorted array approach handles identical elements naturally. The solution still focuses on sums rather than element uniqueness.
Applications
The techniques used in solving this problem extend to other computational problems such as:
- Closest pairs or triples in multi-dimensional space.
- Real-world scenarios like balancing financial portfolios, where closest approximations to a target value are required.
The problem of finding three elements in an array whose sum is closest to a given number is a quintessential problem illustrating optimization in algorithm design. Understanding how to apply sorting with the two-pointer technique helps to efficiently arrive at a solution, offering an insightful view into problem-solving strategies in computer science.

