ProgrammingVery hardCAT · MBA placement

Sorted array a = [1, 2, 3, 5, 8, 9] and limit L = 10. Count the pairs of distinct positions i < j with a[i] + a[j] <= L using two pointers: if a[i] + a[j] <= L, all pairs (i, k) with i <= k < j are valid, so add j - i and move i up; otherwise move j down. What is printed?

Sorted array a = [1, 2, 3, 5, 8, 9] and limit L = 10. Count the pairs of distinct positions i < j with a[i] + a[j] <= L using two pointers: if a[i] + a[j] <= L, all pairs (i, k) with i <= k < j are valid, so add j - i and move i up; otherwise move j down. What is printed?
i = 0; j = n - 1; count = 0
while i < j
    if a[i] + a[j] <= L then count = count + (j - i); i = i + 1
    else j = j - 1
end while
Print count
  1. A. 7
  2. B. 9
  3. C. 3
  4. D. 10

Correct answer: B. 9

The valid pairs are (1,2), (1,3), (1,5), (1,8), (1,9), (2,3), (2,5), (2,8), (3,5), which is 9. A strict inequality drops the pairs summing to exactly 10, counting one pair per i undercounts, and adding a stray 1 is an off-by-one error.

More Pseudocode and Code Tracing questions

Exams that ask this topic