Think Binary Search when you see:
If the answer looks like:
false false false true true true👉 Binary Search is the correct approach.
When to use:
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:
When to use:
Key idea:
If found:
Problems:
When to use:
Lower Bound: First index where value >= target
Upper Bound: First index where value > target
Problems:
When to use:
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:
When to use:
Key idea:
Problems:
When to use:
Problems:
❌ 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
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 🚀