warming up your workspace

Two pointers

Applies to: general, python

The two-pointer technique uses two indices that move through a sequence, often from opposite ends or at different speeds, to replace a nested loop with a single pass. It fits sorted-array pair problems, palindromes, and in-place partitioning.

i, j = 0, len(a) - 1
while i < j:
    s = a[i] + a[j]
    if s == target: return [i, j]
    i, j = (i + 1, j) if s < target else (i, j - 1)

See also: sliding-window, array