← Pattern comparisons

Binary Search vs Two Pointers

Both exploit order, but one halves search space while the other shrinks a range.

Binary Search

O(log n) time, O(1) space

Use When

  • Monotonic condition exists over index or value domain
  • Need index/position/boundary in sorted structure
  • Can discard exactly half each iteration

Avoid When

  • Decision is not monotonic
  • Need pair interactions across both ends
Mental model: Cut the candidate space in half each step.
VS

Two Pointers

O(n) time, O(1) space

Use When

  • Need pair/range relationship in sorted array or string
  • Can move one boundary based on local comparison
  • Window/range invariant is easier than monotonic search

Avoid When

  • No directional rule for moving pointers
  • Need exact boundary via monotonic predicate
Mental model: Squeeze or slide boundaries while preserving invariant.

Decision Checklist

  1. If each check can eliminate half candidates, choose binary search.
  2. If you are pairing values from both ends or maintaining a window, choose two pointers.
  3. For sorted arrays, test both mental models quickly before coding.