ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

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

Correct answer: B. 2

After a match the code moves both pointers, which skips the other copies of the same value. For [1,1,1,1] it finds only two matches, although the true number of index pairs with sum 2 is 6.

More Python Programming questions

Exams that ask this topic