ProgrammingModerateTCS NQT · Wipro pattern

What is printed?

What is printed?
def pairs(a, t):
    a = sorted(a)
    l, r = 0, len(a) - 1
    out = []
    while l < r:
        s = a[l] + a[r]
        if s == t:
            out.append((a[l], a[r]))
            l += 1
            r -= 1
        elif s < t:
            l += 1
        else:
            r -= 1
    return out
print(pairs([3, 1, 4, 2, 5, 6], 7))
  1. A. [(1, 6), (2, 5)]
  2. B. [(1, 6), (3, 4)]
  3. C. [(2, 5), (3, 4), (1, 6)]
  4. D. [(1, 6), (2, 5), (3, 4)]

Correct answer: D. [(1, 6), (2, 5), (3, 4)]

On a sorted array the two pointers move toward each other and report every matching pair. Sorted input 1 to 6 with target 7 gives (1, 6), (2, 5) and (3, 4).

More Python Programming questions

Exams that ask this topic