Loop Code Recur All Articles
Algorithms & Problem Solving

Two Pointers in the Wild: Five Jobs Sorted Streams Do in Production

By Loop Code Recur Algorithms & Problem Solving
Two Pointers in the Wild: Five Jobs Sorted Streams Do in Production

Photo: Cbrasil0, CC BY-SA 4.0, via Wikimedia Commons

Two pointers is the pattern everyone learns for the whiteboard and then never thinks about again. Which is a shame, because once you start noticing it, it is doing a lot of quiet work inside systems you already run.

The setup is always the same: two sorted sequences, one index into each, advance whichever one is behind. Linear time, constant extra space, no hash map, no full materialization. That combination is why it keeps winning on jobs where the data is too big to hold and the sort order is free.

Here are five places it earns its keep.

1. Merging log shards without loading them

You have two or more log files, each already ordered by timestamp. You want one ordered stream out. Read a line from each, compare heads, emit the smaller, advance that pointer.

def merge(a, b):
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i].ts <= b[j].ts:
            yield a[i]; i += 1
        else:
            yield b[j]; j += 1
    yield from a[i:]
    yield from b[j:]

Complexity: O(n + m) time, O(1) auxiliary space beyond the output. The trap: the tail flush. Drop the last two yield from lines and you will silently lose every record after the shorter stream runs out — and it will look fine in dev, where both files are the same size.

2. Collapsing duplicates out of a sorted event stream

After a merge, you often have the same logical event from two sources. If the stream is sorted by a stable key, dedup is a two-pointer walk: compare the read pointer against the write pointer, copy forward only when the key changes.

def compact(events, key=lambda e: e.id):
    w = 0
    for r in range(len(events)):
        if w == 0 or key(events[r]) != key(events[w - 1]):
            events[w] = events[r]
            w += 1
    del events[w:]

Complexity: O(n) time, in place. The trap: comparing against events[r - 1] instead of the last written record. With three or more duplicates in a row, the naive version keeps them all.

3. Reconciling two sorted ID lists in a delta sync

Your local store has a sorted list of IDs. The server sends its sorted list. You need three buckets: added, removed, unchanged.

added, removed, same = [], [], []
i = j = 0
while i < len(local) and j < len(remote):
    if local[i] == remote[j]:
        same.append(local[i]); i += 1; j += 1
    elif local[i] < remote[j]:
        removed.append(local[i]); i += 1
    else:
        added.append(remote[j]); j += 1
removed.extend(local[i:])
added.extend(remote[j:])

Complexity: O(n + m) time, O(1) working space. The trap: advancing both pointers on a match is correct here, but advancing both on a mismatch quietly skips records. Also make sure both lists use the same collation — a numeric ID sorted as a string will break every comparison downstream.

4. Intersecting posting lists in a search index

Term lookups return sorted document IDs. Intersecting them for a multi-term query is a two-pointer walk that skips ahead aggressively: whichever pointer is behind jumps forward until it catches up or passes.

Complexity: O(n + m) worst case, much better in practice when the lists are sparse. The trap: galloping skip logic that is not bounded by the list length. Every fast-forward needs a while guard, or the sparse case turns into an out-of-bounds read on a quiet Sunday.

5. Merge-joining two time series

This is the same idea as a database merge join, and it shows up whenever you need to align two sorted metric streams — application logs against deploy events, ad impressions against billing records, sensor readings against maintenance windows.

while i < len(metrics) and j < len(events):
    if metrics[i].ts < events[j].ts:
        unmatched.append(metrics[i]); i += 1
    elif metrics[i].ts > events[j].ts:
        j += 1
    else:
        yield (metrics[i], events[j]); i += 1; j += 1

Complexity: O(n + m). The trap: one-to-many matches. If several events share a timestamp, advancing j inside the match case discards the rest. Either keep j fixed while metrics[i].ts matches, or accept that you have built a many-to-many join and handle it explicitly.

Why the pattern keeps earning its keep

The selling point is not cleverness. It is that two pointers need no extra memory and no second pass over the data, which matters when the stream is 40 GB and the container has 2 GB of headroom. Hash maps are easier to write and easier to get wrong at scale; a sort plus a merge is boring in the best way.

One habit worth building: write the loop guard as i < len(a) and j < len(b), then immediately write the two tail flushes. Most of the bugs in this pattern are not in the comparison — they are in the cleanup everyone forgets.