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):
passPublic examples
values = [-2, 0, 1, 3], limit = 2gives4values = [2, 3, 4], limit = 1gives0
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
