CS concepts

Two Pointers Explained: Every Variant Interviewers Ask

Updated Dec 4, 2026 · 4 min read

Two pointers keeps two positions in the same list and moves one of them each step, never backwards. Every move rules out one element for good, so the scan is O(n) with O(1) extra memory. The pointers either walk in from both ends (sorted pair, palindrome, container, 3Sum), walk the same way at different speeds (remove duplicates, fast and slow), or start at the back (merge sorted array). On unsorted input where positions matter, use a hash map instead.

Two Pointers Variants reel cover

Key points

  • ●Sorted pair (LeetCode 167): sum too big, move the right pointer; too small, move the left.
  • ●Container With Most Water (LeetCode 11): always move the shorter post.
  • ●3Sum (LeetCode 15): sort, fix one number, run the sorted pair on the rest, skip repeats.
  • ●Same direction (LeetCode 26): the fast pointer reads, the slow pointer writes.
  • ●Merge Sorted Array (LeetCode 88): fill from the back, where the free space is.
Step-by-step visual sheet: Two Pointers Variants
The full visual sheet, made with Edithly.Open the interactive sheet

Why two pointers beats checking every pair

Take a sorted list of a million numbers and ask for two that add up to a target. Checking every pair is about 500 billion checks. Two pointers does it in under a million steps: one pointer on each end, and every step throws one number away for good.

The giveaway words are sorted, pair, in place and palindrome, or a linked list with a loop. The question to ask every time is the same. Which pointer moves, and why is it safe to skip what it leaves behind?

Walking in from both ends

Sorted pair (LeetCode 167). In 1, 2, 4, 6, 8, 11, which two add up to 10? 1 + 11 = 12 is too big, and 11 is too big with anything, so the right pointer steps in. 1 + 8 = 9 is too small, so the left steps in. 2 + 8 = 10. Three looks instead of fifteen pairs.

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

Valid Palindrome (LeetCode 125). Is "Was it a car, or a cat I saw?" the same both ways, ignoring case and anything that isn't a letter or digit? Skip the junk on each side, compare lowercase letters, step both pointers in. It matches to the middle, so it's true. "race a car" fails at the fourth comparison, e against a, and you stop right there. The visual sheet above walks through both checks step by step.

l, r = 0, len(s) - 1
while l < r:
    while l < r and not s[l].isalnum():
        l += 1
    while l < r and not s[r].isalnum():
        r -= 1
    if s[l].lower() != s[r].lower():
        return False
    l += 1
    r -= 1
return True

Container With Most Water (LeetCode 11). For posts 3, 7, 2, 6, 4, 5, the ends give 3 x 5 = 15. Move the shorter post: 7 and 5, four apart, hold 20. Then 12, 12 and 2. The best is 20. Moving the taller post is the classic mistake, because it throws away the only side that could still win.

3Sum (LeetCode 15). Sort 0, -2, 1, 2, -2, 1 into -2, -2, 0, 1, 1, 2. Fix the first -2 and run the sorted pair on the rest looking for 2: you find [-2, 0, 2] and [-2, 1, 1]. Skip the second -2 so you don't find them twice. Sorting costs O(n log n) and the loops O(n squared), well under the O(n cubed) of three nested loops.

Same direction: fast reads, slow writes

Remove Duplicates from Sorted Array (LeetCode 26) keeps each value once in [1, 1, 2, 3, 3, 3, 4] without a second list. The fast pointer reads every number. The slow pointer marks where the next new value goes. New values land in slots 1, 2 and 3, and the function returns 4: the array starts with 1, 2, 3, 4.

slow = 1
for fast in range(1, len(nums)):
    if nums[fast] != nums[fast - 1]:
        nums[slow] = nums[fast]
        slow += 1
return slow

Move Zeroes (LeetCode 283) is the same idea: the slow pointer writes every number that isn't zero.

Fast and slow

Linked List Cycle (LeetCode 141) moves slow one node and fast two. With no loop, fast runs off the end. With a loop, fast gains exactly one node per step, so it can't jump over slow, and they meet.

slow = fast = head
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
    if slow is fast:
        return True
return False

The same pair finds the middle of a list (LeetCode 876): in 1 to 5, slow is on 3 when fast reaches the end.

Merge from the back

Merge Sorted Array (LeetCode 88) merges 2, 5, 6 into 1, 4, 7 followed by three empty slots. Starting at the front would overwrite the 4. Starting at the back, the larger of the two current values goes into the last free slot: 7, 6, 5, 4, 2. When the second list runs out, the 1 is already in place, giving 1, 2, 4, 5, 6, 7 in O(m + n) time.

i, j, k = m - 1, n - 1, m + n - 1
while j >= 0:
    if i >= 0 and nums1[i] > nums2[j]:
        nums1[k] = nums1[i]
        i -= 1
    else:
        nums1[k] = nums2[j]
        j -= 1
    k -= 1

The trap: no order, no pointers

Two Sum (LeetCode 1) gives 3, 8, 1, 5 and a target of 6, and wants positions. The answer is positions 2 and 3 (1 and 5). The list isn't sorted, so moving the right pointer doesn't make the sum smaller, and sorting would scramble the positions you need. Use a hash map: for each number, check whether its partner has already been seen. Two pointers only works when moving a pointer changes the answer in a known direction.

Frequently asked questions

How do I know a problem wants two pointers?

Look for a sorted array or string and a question about a pair or a triple, a request to change the array in place, a palindrome check, or a linked list with a loop or a middle. The key test is whether moving one pointer has a known effect, so you can safely skip what it leaves behind.

Why is two pointers O(n)?

Each step moves one pointer one place, and the pointers never move back or cross. So the total number of moves is at most the length of the list. For a sorted list of a million numbers that's under a million steps, against about 500 billion pair checks for brute force.

Why move the shorter post in Container With Most Water?

The water level is capped by the shorter post. Any other pair that keeps the shorter post is narrower and still capped at the same height, so it can't do better. Dropping the shorter post is the only move that could find more water. For heights 3, 7, 2, 6, 4, 5 the best is 20, between the 7 and the 5.

When should I use a hash map instead of two pointers?

When the input isn't sorted and the answer needs the original positions, as in Two Sum (LeetCode 1). Sorting would scramble the positions, and without an order the pointer move rule breaks. A hash map finds each number's partner in one pass, O(n).

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free