ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
def three_sum(a):
    a = sorted(a)
    out = []
    for i in range(len(a) - 2):
        if i and a[i] == a[i - 1]:
            continue
        l, r = i + 1, len(a) - 1
        while l < r:
            s = a[i] + a[l] + a[r]
            if s < 0:
                l += 1
            elif s > 0:
                r -= 1
            else:
                out.append([a[i], a[l], a[r]])
                l += 1
                while l < r and a[l] == a[l - 1]:
                    l += 1
    return out
print(three_sum([-1, 0, 1, 2, -1, -4]))
  1. A. [[-1, -1, 2], [-1, 0, 1]]
  2. B. [[-1, -1, 2], [-1, 0, 1], [-1, 0, 1]]
  3. C. [[-4, 0, 1]]
  4. D. [[-1, 0, 1], [-1, -1, 2]]

Correct answer: A. [[-1, -1, 2], [-1, 0, 1]]

Sorting lets the code fix one value and move two pointers, skipping repeated values so each triplet appears once. Only -1, -1, 2 and -1, 0, 1 sum to zero.

More Python Programming questions

Exams that ask this topic