When do two pointers work, and why?

Two pointers Mid-level Python 3.13+ Reviewed By Best Latest Apps

Pick the fix

Which problem fits opposite-end two pointers without extra work?

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Find a pair with a given sum in a sorted list

Right: the sum moves predictably as each pointer moves.

Sortedness gives the monotonic behaviour that justifies throwing away one end on every step.

Why not the others?
  • B Find a pair with a given sum in an unsorted list. Without order, moving a pointer does not rule anything out; use a hash map or sort first.
  • C Find the most frequent value. That is a counting question, not a pointer sweep.

30-second answer

Two pointers work when some order lets you discard one candidate per step: sorted values for pair sums, positions for in-place edits, or two sorted inputs for merging. The proof is always the same shape: show the item you drop cannot be part of any remaining answer. Then n steps cover O(n) candidates instead of O(n²) pairs.

Practise saying it · 45 s. No recording, just a timer

Explain how to recognise a two-pointer problem.

Say your answer out loud, then check which of these points you covered:

  • Order that allows discarding
  • Opposite ends vs same direction
  • State why a move is safe

Deep dive

Opposite ends: sorted data and a condition that grows or shrinks monotonically with each pointer.

Same direction: a read pointer explores, a write pointer or a slower pointer marks progress (in-place edits, windows).

If you cannot state the discard argument, the pattern probably does not apply; consider a hash map or sorting first.

Common mistakes

  • Applying opposite-end pointers to unsorted data.
  • Moving a pointer without a reason that rules out the dropped item.

Senior take & follow-ups

Say the discard argument for your specific problem; generic 'two pointers is O(n)' is not enough.

Follow-up questions

Think of your answer first, then open the hint.

  1. How is a sliding window related?

    Show hint

    It is same-direction two pointers where the region between them is the candidate answer.

  2. When is sorting first worth it?

    Show hint

    When the O(n log n) sort enables an O(n) sweep that replaces an O(n²) search.

What each operation costs: Arrays · Array Operations

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.