Data Structures & AlgorithmsHardCodeforces Div2 C · two pointers

Problem: Count the pairs (i < j) with a[i] + a[j] < 6 for the array [5, 1, 4, 2, 3].

Problem: Count the pairs (i < j) with a[i] + a[j] < 6 for the array [5, 1, 4, 2, 3].
def count(a, T):
    a = sorted(a)
    i, j = 0, len(a) - 1
    ans = 0
    while i < j:
        if a[i] + a[j] < T:
            ans += j - i
            i += 1
        else:
            j -= 1
    return ans
print(count([5, 1, 4, 2, 3], 6))
What is printed?
  1. A. 3
  2. B. 5
  3. C. 6
  4. D. 4

Correct answer: D. 4

After sorting, the two-pointer scan counts (1,2), (1,3), (1,4) and (2,3), giving 4. The pair (2,4) sums to exactly 6 and must not be counted.

More Coding Interview Problems questions

Exams that ask this topic