🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →
Day 25 - Two PointersBasic Questions

Basic Two-Pointer Questions

Six warm-ups to lock the three templates into muscle memory. Two opposite-ends, two same-direction, two fast-and-slow — one of each shape from each side of the family.

For each problem, force yourself through the pattern-spotting checklist before peeking:

  1. Which flavor does the problem want?
  2. What are the pointers’ roles?
  3. What’s the movement rule?
  4. What’s the stopping condition?

1. Reverse String (in place)

Given a character array s, reverse it in place.

Flavor: opposite-ends. Pointers: l = 0, r = n - 1. Movement: swap and move both inward.

Time: O(n). Space: O(1).

2. Valid Palindrome

Given a string s, return true if it’s a palindrome after lowercasing and removing non-alphanumerics.

Flavor: opposite-ends. Inner while loops skip junk characters.

Time: O(n). Space: O(1).

3. Two Sum II (sorted array)

Given a 1-indexed sorted array numbers and target t, return the two 1-indexed positions whose values sum to t.

Flavor: opposite-ends. Movement: if sum too small, l++; if too big, r--.

Time: O(n). Space: O(1).

4. Move Zeroes

Given an integer array nums, move all 0s to the end while keeping the relative order of non-zero elements. In place.

Flavor: same-direction. Filter: “non-zero.” Backfill with zeros after the read loop.

Time: O(n). Space: O(1).

5. Middle of the Linked List

Return the middle node. For even-length lists, return the second of the two middles.

Flavor: fast and slow. fast moves 2 steps for every 1 step of slow.

Time: O(n). Space: O(1).

6. Linked List Cycle

Given the head of a singly linked list, return true if it has a cycle.

Flavor: fast and slow (Floyd’s). If a cycle exists, fast eventually meets slow inside it.

Time: O(n). Space: O(1).

Mini-quiz

In Reverse String, why use opposite-ends pointers instead of building a new reversed string?
In Move Zeroes (overwrite + backfill version), why do we need the second loop?
In Middle of the Linked List, when fast lands on the LAST node (not past it), what's slow at?

Next: the ten practice problems — every two-pointer flavor represented, with the movement-rule justification for each.