array
algorithm
sum
optimization
coding

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:

  1. Sort the Array: The solution begins by sorting the input array. Sorting helps in efficiently finding the required sum using a two-pointer strategy.
  2. Initialize Variables: We need a variable to keep track of the closest sum we encounter as we iterate through the array. Initialize closestSum with the sum of the first three numbers as a starting point.
  3. 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 closestSum if the calculated sum is closer to the target than the previous closestSum.
  4. Adjust Pointers:
    • If the sum is less than the target, increment the left pointer to increase the sum.
    • If the sum is greater than the target, decrement the right pointer to decrease the sum.
  5. Continue Until Completion:
    • Repeat until all possible combinations of three elements are assessed.
    • Return the closestSum after exiting the loop.

Example

Let's take an example array and a target to illustrate the approach.

python
arr = [-1, 2, 1, -4]
target = 1

Step-by-Step Solution:

  1. Sort the array: [-4, -1, 1, 2]
  2. Initialize closestSum to the first three numbers: -4 + (-1) + 1 = -4
  3. Iterate over each element:
    • For i = 0, arr[i] = -4:
      • left = 1, arr[left] = -1
      • right = 3, arr[right] = 2
      • Calculate currSum = -4 + (-1) + 2 = -3
      • Update closestSum to -3 since |-3 - 1| < |-4 - 1|
      • currSum < target, increment left
    • For i = 1, arr[i] = -1:
      • left = 2, arr[left] = 1
      • right = 3, arr[right] = 2
      • Calculate currSum = -1 + 1 + 2 = 2
      • Update closestSum to 2 since |2 - 1| < |-3 - 1|
      • currSum > target, decrement right

After iterating through each element, the closest sum calculated is 2.

Complexity

  • Time Complexity: Sorting the array takes O(nlogn)O(n \log n) and iterating through the elements with the two-pointer approach results in a time complexity of O(n2)O(n^2). Thus, the total time complexity is O(n2)O(n^2).
  • Space Complexity: The space complexity is O(1)O(1) if we don't consider the input array as additional space.

Key Points Summary

AspectDetails
Problem TypeOptimization, Array Traversal
Efficient ApproachSorting + Two-pointer Technique
Time ComplexityO(n2)O(n^2) (Due to double iteration)
Space ComplexityO(1)O(1) (Ignoring input array storage)
AssumptionsExactly 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.


Course illustration
Course illustration

All Rights Reserved.