Skip to content
Lesson 3 of 10 · Coding Interview Prep: Data Structures and Algorithms

Two pointers

Walk two indexes through a list, usually from both ends, to solve in O(n) without extra memory.

22 min

Two pointers means keeping two indexes and moving them according to a rule, instead of using nested loops. It works best on sorted data, or on problems with a symmetric structure like palindromes.

Start left = 0 and right = len(a) - 1, then move them towards each other.

python4 lines
left, right = 0, len(a) - 1
while left < right:
    ...
    # move left up, or right down, but never both blindly

The skill is knowing which pointer to move. In a sorted list, when you look for pairs with a sum:

  • if a[left] + a[right] is too big, the right value is too large with any left partner, so right -= 1;
  • if it is small enough, the left value works with every item up to right, so you can count them all and then left += 1.

Each step discards at least one item for good, so the whole thing is O(n) time and O(1) space, against O(n²) for checking every pair.

A fast and a slow pointer both move forward: the slow one marks where the next kept item goes, and the fast one scans. This removes duplicates from a sorted list, or squeezes out unwanted items, in place.

Compare the two ends and move inward:

python6 lines
l, r = 0, len(s) - 1
while l < r:
    if s[l] != s[r]:
        return False
    l += 1; r -= 1
return True

To skip characters that do not count (spaces, punctuation), advance l and r past them first.

Hints in the problem: sorted input, pair or triple with a sum, in place, palindrome, merge two sorted lists. If the input is not sorted, sorting first costs O(n log n) and is often still worth it, but beware if you must keep original indexes.

The decision at each step. One pointer always moves, so the loop ends after at most n steps.

Exercise7 checks
python

A shop sorts its prices from cheapest to dearest. Write count_pairs_within(prices, budget): the number of pairs of different items (positions i < j) whose prices add up to at most budget. prices is already sorted ascending. Aim for O(n).

count_pairs_within([1, 2, 3, 4], 5) is 4: (1,2), (1,3), (1,4) and (2,3).

Your code must satisfy

  • count_pairs_within([1, 2, 3, 4], 5)→4example
  • count_pairs_within([6, 7, 8], 5)→0none fit
  • count_pairs_within([1, 1, 1, 1], 10)→6all fit
  • count_pairs_within([], 5)→0empty
  • count_pairs_within([2], 5)→0single
  • count_pairs_within([2, 2, 3, 3], 5)→5duplicates
starter code2 lines
def count_pairs_within(prices, budget):
    pass
Exercise7 checks
python

Write is_palindrome(s) returning True if s reads the same forwards and backwards when you ignore everything except letters and digits, and ignore capital letters. An empty string counts as a palindrome. Use two pointers (no building a reversed copy).

Your code must satisfy

  • is_palindrome("A man, a plan, a canal: Panama")→truesentence
  • is_palindrome("race a car")→falsenot
  • is_palindrome("")→trueempty
  • is_palindrome(".,!")→truepunctuation only
  • is_palindrome("1b1")→truedigits and letters
  • is_palindrome("ab")→falsetwo chars
starter code2 lines
def is_palindrome(s):
    pass
Common misconception

“Two pointers works on any list.”

The code looks simple, so it feels general.

What is actually true

The "move this pointer, never revisit" logic relies on order. On an unsorted list, moving a pointer can discard a valid answer. Sort first (O(n log n)) or use a hash table.

How to catch yourself

Before using two pointers, ask: what fact about the data tells me which pointer to move?

  • Two pointers replace a nested loop with one pass: O(n) time, O(1) space.
  • Opposite-end pointers need sorted data or symmetry; same-direction pointers (slow and fast) work in place.
  • Always know why moving a pointer cannot lose an answer.
  • Guard loops with l < r so the pointers never cross.
Check yourself

Pointer checks.

1Multiple choice

On a sorted list, a[l] + a[r] is larger than the target. Which pointer moves?

  • A`l` forward
  • B`r` backward
  • CBoth
  • DNeither
2Multiple choice

What is the extra space of the opposite-end pointer scan?

  • AO(n)
  • BO(log n)
  • CO(1)
  • DO(n²)
3Multiple choice

Which problem is a natural fit?

  • ACount words in a text
  • BFind a pair with a sum in a sorted list
  • CBuild a binary tree
  • DFind the median of a stream
4Numeric answer

How many pairs i < j exist among 5 items?

5Multiple choice

Why can the pointer scan fail on unsorted data?

  • APython forbids it
  • BMoving a pointer may discard a valid pair
  • CIt is too slow
  • DIt needs recursion

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.