Skip to Content

Two indices march through an array (or one list each) at different speeds or directions.

Data Flow

array   [1, 4, 6, 8, 10, 15]
indices  ^                ^
         L                R          (left + right -- converge)

         or

linked   A -> B -> C -> D -> E
indices  ^         ^
         slow      fast       (fast steps twice per slow)

When to use

How it works

Converging pointers: L=0, R=n-1. Move L or R based on the comparison. Fast/slow: both start at the head; fast moves 2x speed. Useful for cycle detection or finding the middle.

Code (Two Sum on sorted array)

def two_sum_sorted(nums, target):
    l, r = 0, len(nums) - 1
    while l < r:
        s = nums[l] + nums[r]
        if s == target:    return [l, r]
        if s <  target:    l += 1
        else:              r -= 1
    return []

Pitfalls

Analogy

Two people searching a book from opposite ends of an index — if the sum is too low, the left one reads further; too high, the right one goes back.

Interview tip: If the array is sorted and you need pairs/triplets, two pointers is almost always the intended O(N) solution.

Advertisement