Two Pointers Cheat Sheet
Walk two indices through the same list, usually from both ends, so a comparison problem finishes in one pass instead of a nested loop.
When to reach for it
- You need a pair, or a small fixed group, of elements that satisfy some condition against a target.
- You are checking whether a list or string reads the same from both directions, like a palindrome.
- A brute-force answer nests two loops (O(n^2)), but the data is sorted or the order does not 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 are looking for.
- Set up the walk. Two pointers at opposite ends. Every problem here starts by placing them.
- Walk until they meet. The loop never changes. Strict <, never <=.
- Decide and move. Your problem lives here: the check, and which pointer moves.
- Answer. Return the find, or the no-match answer.
Watch out
- This only works cleanly when the list is sorted, or order does not matter. Sort first if it is not.
- Every inner loop that nudges a pointer needs its own bound check, like left < right in Valid Palindrome, or you will walk off the end of the string.
- The loop condition is strict (<), not <=. Once the pointers meet or cross, there is nothing left to compare.
How to earn it
Solve half of the Two Pointers problems on InterviewCrunch and the sheet is yours. Free accounts included. Members can download every sheet right away.
Every pattern has a sheet. See the full set.
