Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit.

Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit.
def pairs_below(a, limit):
    i, j, c = 0, len(a) - 1, 0
    while i < j:
        if a[i] + a[j] < limit:
            c += j - i
            i += 1
        else:
            j -= 1
    return c
print(pairs_below([1, 3, 4, 6, 9], 10))
What is printed?
  1. A. 4
  2. B. 6
  3. C. 5
  4. D. 3

Correct answer: C. 5

If a[i] + a[j] < limit then a[i] pairs with every index i+1..j, so add j − i at once. Trace: 1 + 9 = 10 is not below the limit so j moves; 1 + 6 adds 3; 3 + 6 adds 2; 4 + 6 fails and the pointers meet: 5 pairs ((1,3),(1,4),(1,6),(3,4),(3,6)). Counting (1,9) as valid gives the trap 6. Adding 1 per step instead undercounts. O(n) after sorting.

More Coding Interview Problems questions

Exams that ask this topic