Count pairs below a limit
Count how many pairs of positions in a list have values adding up to strictly less than a limit.
count_pairs_below([1, 2, 3, 4], 6) # 4The pairs are 1+2, 1+3, 1+4 and 2+3.
Two pointers on sorted data
Sort first, then place left at the smallest value and right at the largest.
- If
values[left] + values[right] < limit, thenleftpairs successfully with every position fromleft + 1throughright, because those values are all no larger. That isright - leftpairs at once. Moveleftup. - Otherwise the largest value is too big to pair with
leftor anything after it. Moverightdown.
Each step moves a pointer, so the pass is linear. Remember to sort a copy, since the input belongs to the caller.
Your task
Write count_pairs_below(numbers, limit) returning the number of index pairs i < j with numbers[i] + numbers[j] < limit, in O(n log n) time and without changing the input.
The explanation opens here once every check passes.