ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def closest3(a, t):
    a = sorted(a)
    best = None
    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 best is None or 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))
  1. A. 1 0
  2. B. 2 1
  3. C. 2 0
  4. D. 3 0

Correct answer: C. 2 0

Sorting and two pointers track the sum nearest to the target. For [-1, 2, 1, -4] the best sum is 2, and [0, 0, 0] can only give 0.

More Python Programming questions

Exams that ask this topic