Sorted input: two pointers. Unsorted: the dict, unless memory is the constraint
Here are two pointers and the dict against checking every pair. The sizes are 0, 2, 4, ... and the target is odd, so no pair exists and every version must do all its work:
| n, pairs | Every pair, ms | Two pointers, ms | Dict, ms |
|---|---|---|---|
| 1,000, 499,500 | 15.8 | 0.046 | 0.051 |
| 2,000, 1,999,000 | 64.5 | 0.097 | 0.109 |
| 4,000, 7,998,000 | 255.8 | 0.185 | 0.209 |
| 8,000, 31,996,000 | 1,036.3 | 0.382 | 0.411 |
Python 3.12, best of several runs with timeit, on the laptop these numbers come from.
Two pointers and the dict are both O(n), and close in time. The difference is memory. On a million sorted sizes, the dict's peak was 78.66 MiB by tracemalloc, Python's memory tracer. Two pointers allocated under 0.01 MiB.
The catch is the word sorted. Sorting a million random integers took 139.8 ms, more than the dict's whole pass at 72.4 ms. Sorting also scrambles the original positions.
So: sorted input, two pointers. Unsorted input, the dict, unless memory is the constraint.
The editor holds the start of pairs_within, with lo and hi at the two ends of a sorted price list. Finish the loop so it counts a whole row of pairs after one comparison.