core pattern

Binary Search

Divide and conquer on sorted data. Repeatedly halve the search space by comparing the middle element. Works on sorted arrays, rotated arrays, or any monotonic function.

Time

O(log n)

Space

O(1)

🧠Mental Model

Number guessing game — "higher" or "lower" eliminates half the possibilities each time.

Verbal cue: Calculate mid, compare, halve the search space

🎯Recognition Triggers

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

Sorted array searchFind boundary (first/last occurrence)Rotated sorted arraySearch insert positionMinimize/maximize with constraintSquare root, nth rootPeak element

💡Interview Tips

  • 1Always mention the array must be sorted (or have monotonic property)
  • 2Explain your loop invariant: "target is always in [left, right]"
  • 3For boundary problems, continue searching even after finding target
  • 4Binary search on answer space is a powerful technique for optimization

⚠️Common Mistakes

  • Integer overflow: (left + right) / 2 — use left + (right - left) / 2
  • Infinite loop: forgetting to move left or right by 1
  • Off-by-one: left <= right vs left < right depends on problem
  • Not recognizing binary search applies to answer space, not just arrays