DEV Community

Anurag Goel
Anurag Goel

Posted on Originally published at algosimplified.dev

Two Pointers Pattern

This article first appeared on AlgoSimplified. That URL is canonical. The full lesson has exercises, a short quiz, and a link to a longer two-pointers guide. This is a shorter cut of the same lesson.

The two-pointers pattern uses two indices that move through a sequence, usually from the ends or in the same direction. Each comparison has to justify discarding one element, which is what keeps the scan linear rather than quadratic.

When it applies

  • The input is sorted (or you can sort it) and you need pairs or triples with a target sum.
  • The problem is symmetric: palindromes, reversing, comparing both ends.
  • You need to partition in place (move zeroes, Dutch flag).
lo, hi = 0, len(a) - 1
while lo < hi:
    if condition_met(a[lo], a[hi]):
        record_answer()
    elif need_bigger:
        lo += 1
    else:
        hi -= 1
Enter fullscreen mode Exit fullscreen mode

Each step discards one element for good, so the loop is O(n).

Three worked examples

"""Two pointers on sorted or symmetric input."""


def pair_with_sum(sorted_nums, target):
    lo, hi = 0, len(sorted_nums) - 1
    while lo < hi:
        s = sorted_nums[lo] + sorted_nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1   # need a bigger sum: only moving lo right can help
        else:
            hi -= 1   # need a smaller sum
    return None


def three_sum(nums):
    nums = sorted(nums)
    out = []
    for i in range(len(nums) - 2):
        if i and nums[i] == nums[i - 1]:
            continue  # skip duplicate anchors
        lo, hi = i + 1, len(nums) - 1
        while lo < hi:
            s = nums[i] + nums[lo] + nums[hi]
            if s < 0:
                lo += 1
            elif s > 0:
                hi -= 1
            else:
                out.append([nums[i], nums[lo], nums[hi]])
                lo += 1
                while lo < hi and nums[lo] == nums[lo - 1]:
                    lo += 1
    return out


def max_water(heights):
    lo, hi, best = 0, len(heights) - 1, 0
    while lo < hi:
        best = max(best, (hi - lo) * min(heights[lo], heights[hi]))
        if heights[lo] < heights[hi]:
            lo += 1  # the shorter wall limits the area; moving the taller one can't help
        else:
            hi -= 1
    return best


if __name__ == "__main__":
    print(pair_with_sum([1, 3, 4, 6, 8, 11], 10))
    print(three_sum([-1, 0, 1, 2, -1, -4]))
    print(max_water([1, 8, 6, 2, 5, 4, 8, 3, 7]))
Enter fullscreen mode Exit fullscreen mode

Output:

(2, 3)
[[-1, -1, 2], [-1, 0, 1]]
49
Enter fullscreen mode Exit fullscreen mode

Why the moves are safe

  • Pair sum: if a[lo] + a[hi] is too small, pairing a[lo] with anything left of hi is even smaller, so a[lo] cannot be in any answer. Discard it. That is why the array has to be sorted: moving lo right increases the sum, moving hi left decreases it. Here 4 + 6 is the pair at indices (2, 3).
  • 3Sum: sort, fix the first number, then run pair sum on the rest. Skip equal anchors and equal lo values to avoid duplicate triples, rather than stuffing tuples into a set. O(n²) overall, which is the best known for this problem in practice.
  • Container with most water: the area is limited by the shorter wall. Moving the taller wall inward can only shrink the width without raising that limit, so you always move the shorter one. On [1, 8, 6, 2, 5, 4, 8, 3, 7] the area is 49.

Related variants

  • Same direction (read/write pointers): remove duplicates in place, move zeroes. One pointer scans, the other marks where to write.
  • Opposite ends on strings: valid palindrome, reverse vowels.
  • When the window between the pointers must satisfy a condition, that's the sliding window pattern.

For more practice, the two pointers problems on the cheat sheet, and the two pointers technique guide with eight more worked problems (including trapping rain water and sort colors). The full two pointers lesson also has exercises (valid palindrome, move zeroes, 4Sum) and a short quiz, as part of the free DSA Patterns course.

Top comments (0)