core pattern

Two Pointers

Use two pointers to traverse an array from different positions, often moving toward each other or in the same direction. Perfect for problems involving pairs, sorted arrays, or in-place modifications.

Time

O(n)

Space

O(1)

🧠Mental Model

Squeezing a toothpaste tube from both ends — you converge toward the middle, processing as you go.

Verbal cue: Start at edges, move inward based on comparison

🎯Recognition Triggers

When you see these patterns in a problem, consider this approach:

Sorted arrayFind pair with target sumRemove duplicates in-placePalindrome checkContainer with most waterThree sum / Four sumMerge sorted arrays

💡Interview Tips

  • 1Always clarify if the input is sorted — this determines the approach
  • 2For "find all pairs" problems, continue searching after finding one
  • 3Mention O(1) space as a key advantage over hash map approaches
  • 4Draw the array and show pointer movement to visualize

⚠️Common Mistakes

  • Forgetting the array must be sorted for convergent two pointers
  • Off-by-one errors with left < right vs left <= right
  • Not handling duplicates when required (e.g., 3Sum)
  • Modifying pointers incorrectly after finding a match