ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def three_less(a, t):
    a = sorted(a)
    n = len(a)
    c = 0
    for i in range(n - 2):
        l, r = i + 1, n - 1
        while l < r:
            if a[i] + a[l] + a[r] < t:
                c += r - l
                l += 1
            else:
                r -= 1
    return c
print(three_less([-2, 0, 1, 3], 2))
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: C. 2

Fix the first index and move two pointers. When a sum is below target, every index between left and right also works, so the code adds r - l at once. For [-2,0,1,3] and target 2 that gives 2.

More Python Programming questions

Exams that ask this topic