Topics
DSAeasy

Two Pointers

When the array is sorted, two indices walking toward each other often beat nested loops.

Two pointers is the pattern you reach for when the input has order — sorted arrays, palindromes, or "find a pair that sums to X."

When it applies

Classic: pair with target sum

Given a sorted array, find two numbers that add up to target.

python
def two_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None:
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return None

Complexity

ApproachTimeSpace
Brute forceO(n²)O(1)
Two pointersO(n)O(1)
Hash map (unsorted)O(n)O(n)

In an interview, say the sorted assumption out loud. If the array isn't sorted, ask whether you may sort — that's often the difference between O(n) and O(n log n).