2/32
Part 1 of 6 · Two pointersLearn and do

Two indexes instead of two loops

A lot of coding questions ask about pairs or stretches of a list. Two files whose sizes add up to a target. The longest stretch of a log with no repeat. How many requests a client sent in the last ten seconds.

The first code that comes to mind tries every pair or every stretch: two nested loops, O(n²). This lesson swaps the two loops for two indexes that each move in one direction only. Each index takes at most n steps, so the whole pass is O(n).

The pieces build to the practice problem: three questions about an API gateway's request log. The first two-index trick works on sorted data.

On sorted data, start one pointer at each end

In the hash-maps lesson's worked example you found two files that fill a disk exactly, with a dict from size to position. That cost O(n) time and O(n) memory. When the sizes arrive sorted, you can drop the dict. Put lo on the smallest size and hi on the largest, and look at their sum:

# sizes sorted, low to high
def pair_with_sum(sizes, target):
    lo, hi = 0, len(sizes) - 1
    while lo < hi:
        total = sizes[lo] + sizes[hi]
        if total == target:
            return lo, hi
        if total < target:
            # sizes[lo] is too small even with the biggest partner left
            lo += 1
        else:
            # sizes[hi] is too big even with the smallest partner left
            hi -= 1
    return None

sizes = [100, 250, 300, 450, 700, 800, 1200]
print(pair_with_sum(sizes, 1150))
Predict

sizes are 100, 250, 300, 450, 700, 800, 1200, and the target is 1150. Which two add up to it?

Pick one to see what it prints.
Pick an answer above to see the rest