Binary Search Patterns That Solve 80% of LeetCode Problems

When Should Binary Search Click in Your Mind?

Think Binary Search when you see:

  • Sorted array / rotated sorted array
  • Minimum / Maximum answer
  • Capacity / speed / days / size
  • "Can we do it?" → Yes / No type logic

If the answer looks like:

false false false true true true

👉 Binary Search is the correct approach.


Pattern 1: Classic Binary Search (Search an Element)

When to use:

  • Array is sorted
  • Find exact target

Template:

let l = 0, r = nums.length - 1;

while (l <= r) {
  const mid = l + Math.floor((r - l) / 2);
  if (nums[mid] === target) return mid;
  if (nums[mid] < target) l = mid + 1;
  else r = mid - 1;
}
return -1;

Problems:


Pattern 2: First / Last Occurrence (Duplicates)

When to use:

  • Sorted array
  • Duplicates exist
  • Need first or last position

Key idea:

If found:

  • First → move left
  • Last → move right

Problems:


Pattern 3: Lower Bound / Upper Bound

When to use:

  • Find insertion position
  • First value ≥ target or > target

Lower Bound: First index where value >= target

Upper Bound: First index where value > target

Problems:


Pattern 4: Binary Search on Answer (MOST IMPORTANT)

When to use:

  • Question asks for minimum / maximum answer
  • You can check an answer using Yes / No

Pattern: Find minimum X such that isPossible(X) is true

Template:

let l = min, r = max, ans = -1;

while (l <= r) {
  const mid = Math.floor((l + r) / 2);
  if (isPossible(mid)) {
    ans = mid;
    r = mid - 1;
  } else {
    l = mid + 1;
  }
}
return ans;

Problems:


Pattern 5: Rotated Sorted Array

When to use:

  • Sorted array rotated at some pivot

Key idea:

  • One half is always sorted
  • Decide which half to discard

Problems:


Pattern 6: Binary Search on Matrix

When to use:

  • Matrix rows sorted
  • Treat matrix like a 1D array

Problems:


Common Mistakes to Avoid

❌ Using binary search on unsorted data

mid = (l + r) / 2 (overflow risk)

✅ Always use:

mid = l + Math.floor((r - l) / 2);

❌ Infinite loops

✅ Ensure l or r always moves


Must-Solve Binary Search Questions (In Order)

Easy

Medium

Hard


Final Tip (Interview Gold)

If you can answer:

"Can I validate a candidate answer using Yes / No?"

👉 Binary Search is the correct solution.

If this helped you, consider upvoting 👍
Happy Coding 🚀

Comments (0)