Core pattern

Two pointers: two friends, one row of lockers

Learn the two pointers pattern through one picture you won’t forget, worked on Two Sum II.

The example problem

Given a list of numbers sorted from small to large and a target, find the two numbers that add up to the target and return their positions (LeetCode counts from 1).

Input:  [1, 3, 4, 6, 8, 11, 13, 15], target = 10
Output: [3, 4]   (positions of 4 and 6, counting from 1)

Picture it

Picture a row of lockers numbered in increasing order, with one friend at each end. They add their two locker numbers. Too big? The friend on the right steps left to a smaller locker. Too small? The friend on the left steps right to a bigger one. Because the row is sorted, each step safely rules out a locker, and they meet the answer without trying every pair.

The key idea

Sorted input lets two pointers squeeze inward: sum too big → move right pointer left, too small → move left pointer right. O(n).

Python

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

Practise two pointers

NeetCode 150 problems that use it

Two Pointers ·