Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Two pointers

Two indices walking a sorted or paired structure, each step ruling out one candidate for good.


When it applies

1 3 4 5 7 11 lo hi too small → lo++ too big → hi-- each comparison removes one index for good

Reach for two pointers when the input is sorted, or when the answer involves a pair or a window whose ends move monotonically. The test is whether you can argue that one end can be discarded for ever after a comparison. If you cannot make that argument, you probably want a hash map or a sort first.

Signals in the question: "sorted array", "pair that sums to", "closest", "remove duplicates in place", "partition", "palindrome".


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

lo, hi = 0, len(a) - 1
while lo < hi:
    if condition(a[lo], a[hi]):
        return (lo, hi)
    elif too_small(a[lo], a[hi]):
        lo += 1        # a[lo] can never be part of the answer
    else:
        hi -= 1        # a[hi] can never be part of the answer

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.