Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the three numbers in an array whose sum is closest to a target.

Problem: Find the three numbers in an array whose sum is closest to a target.
def closest3(a, t):
    a.sort(); best = a[0] + a[1] + a[2]
    for i in range(len(a) - 2):
        l, r = i + 1, len(a) - 1
        while l < r:
            s = a[i] + a[l] + a[r]
            if abs(s - t) < abs(best - t): best = s
            if s < t: l += 1
            elif s > t: r -= 1
            else: return s
    return best
print(closest3([-1, 2, 1, -4], 1), closest3([0, 0, 0], 1), closest3([1, 1, 1, 0], -100))
What is printed?
  1. A. 2 0 1
  2. B. 0 0 2
  3. C. 2 0 2
  4. D. 3 0 2

Correct answer: C. 2 0 2

Sort, fix one element, two-pointer the rest, keeping the closest sum: −1 + 1 + 2 = 2 (distance 1). [0, 0, 0] can only make 0. For target −100 the closest is the smallest possible triple of [0, 1, 1, 1]: 0 + 1 + 1 = 2 (a single 1 is not a triple). O(n²).

More Coding Interview Problems questions

Exams that ask this topic