ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def cnt(xs, T):
    xs = sorted(xs)
    lo, hi, total = 0, len(xs) - 1, 0
    while lo < hi:
        if xs[lo] + xs[hi] <= T:
            total += hi - lo
            lo += 1
        else:
            hi -= 1
    return total
print(cnt([1, 2, 3, 4], 5))
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 6

Correct answer: A. 4

Two-pointer count of pairs with sum at most T. Whenever xs[lo] + xs[hi] <= T, every index between lo and hi-1 also pairs with hi, so hi - lo pairs are counted. The pairs with sum <= 5 are (1,2), (1,3), (1,4), (2,3), so the answer is the count of those, 4.

More Python Programming questions

Exams that ask this topic