Two Pointers Cheat Sheet

You walk two pointers through the same list, usually from both ends. One pass does the work a nested loop would.

When to use it

  • You need a pair or a small group of elements that hit some condition against a target.
  • You're checking whether a list or string reads the same from both ends, like a palindrome.
  • The brute-force answer nests two loops at O(n^2), but the data is sorted or order doesn't matter.
  • You want O(1) extra space instead of a hash map or a second array.

What's on the sheet

Every problem here is the same walk. Step 3 says what you're looking for.

  1. Set up the walk. Every problem starts by placing a pointer at each end.
  2. Walk until they meet. The loop never changes. Use < here, not <=.
  3. Decide and move. Your problem lives here. It sets the check and picks which pointer moves.
  4. Answer. Return what you found, or the no-match answer.

Watch out

  • This only works cleanly when the list is sorted or order doesn't matter. If it isn't sorted, sort it first.
  • Any inner loop that nudges a pointer needs its own bound check, like left < right in Valid Palindrome. Skip it and you'll walk off the string.
  • The loop condition is strict (<), not <=. Once the pointers meet or cross, there's nothing left to compare.

How to earn it

Solve half of the Two Pointers problems and the sheet is yours. A free account works fine, and everyone earns their sheets the same way.

Every pattern has a sheet. See the full set.