Two Pointers
Two indices moving through the data so each step rules work out instead of repeating it.
- inside the window
- active this step
- ruled out
- result
Pointers at both ends
left points at −4, the smallest value; right points at 13, the largest.
VARIABLES
- left
- 0
- right
- 7
- total
- -
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Two indices walk an array or string - toward each other or in the same direction. A comparison decides which one moves.
Why it matters
It replaces an O(n²) pair scan with one O(n) pass when the data has order you can use.
Think of it like this
Two friends reading a sorted price list from opposite ends to find two items that exactly fit a budget.
Use it when
- Sorted input and a pair or triplet condition
- Rewriting an array in place
- Comparing from both ends, as in palindromes
Avoid it when
- Unsorted input where original indices matter - use a hash map
- No comparison tells you which pointer to move
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Converging pointers | O(n) | O(1) |
| Check every pair | O(n²) | O(1) |
| Sort first, then pointers | O(n log n) | O(1) to O(n) |
Often confused with: sliding window - also two indices, but it tracks a running total or count for the range between them.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- n ≤ 10⁵ rules out checking every pair
- O(1) extra space rules out a hash map
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- while left <= right lets an element pair with itself
- Running it on unsorted input
- Moving both pointers after a mismatch can skip the only valid pair
Edge cases to test
- An empty or single-element array
- No valid pair
- Duplicates like [2, 2, 3] with target 4 - returns [0, 1]
Knowledge check
Quick check to lock in the intuition.
nums = [1, 4, 6, 8, 11], target = 10. The first check is 1 + 11 = 12. What happens next?
Practice
Apply what you just watched on real interview problems.