Skip to contentKEEP THE CRAFTTHE SANCTUARY

Discard Pairs with Two Pointers

Count pairs in a sorted list whose sum is below a limit, counting a whole block of partners at once.

The problem

Implement count_pairs_below(values, limit). values is sorted in non-decreasing order. Return how many index pairs i < j have values[i] + values[j] < limit. For example, [-2, 0, 1, 3] with limit 2 gives 4: the pairs are (-2, 0), (-2, 1), (-2, 3) and (0, 1). Try to do it in one pass, in O(n) time.

Starter code

def count_pairs_below(values, limit):
    pass

Public examples

  1. values = [-2, 0, 1, 3], limit = 2gives4
  2. values = [2, 3, 4], limit = 1gives0

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.