Revision: Binary Search

This is a quick revision sheet for Binary Search DSA pattern.
π Here is the link to the OG full-length post Binary Search Pattern β The Interviewer's Favorite
Use this page for last-minute interview prep, fast memory refresh, or revisiting key templates and pitfalls.
β When to Use Binary Search
- Array is sorted
- Problem asks to find/insert/search a value
- Decision space is monotonic (e.g. if X works, X+1 works too)
- Problem wants to minimize/maximize a number under constraints β Use Binary Search on Answer
- Precision answer needed (like square root) β Use Decimal Binary Search
π§ 5 Must-Know Binary Search Templates
Classic Search (
while (left <= right)
) β For finding exact value in a sorted arrayInsert Position / Lower Bound (
while (left < right)
) β First element β₯ targetFirst/Last Position β Two-pass binary search for [first, last] indices
Binary Search on Answer β No array; search over range
[min, max]
β UseisValid(mid)
to simulateDecimal Precision Search β Loop ~100 times to get accurate float value
β Used for square roots, min speed with floating-point limits
β οΈ Pitfalls to Avoid
- β Donβt write
left = mid
orright = mid
- β
Always shrink window:
left = mid + 1
orright = mid - 1
- Loop bugs = Your range isn't shrinking
- Know when to use
left < right
vs.left <= right
π§ͺ Binary Search on Answer β How to Think
βIf I guess this number, can I make it work?β
true
β Itβs feasible β try smaller βright = mid
false
β Itβs not enough β try bigger βleft = mid + 1
Use isValid(mid)
to simulate the guess (e.g. can Koko finish bananas at this speed?).
π Always Dry Run These Edge Cases
- Empty array
- Single-element array
- Target not found
- Target at edges (first or last)
- Duplicates (for left/right bounds)
- Even vs. odd length inputs
π§ Want a full walkthrough with code, dry runs, and examples?
π Read the full Binary Search Deep Dive here β
Subscribe to my newsletter
Read articles from LilSardarX directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

LilSardarX
LilSardarX
Iβm figuring things out in tech β and blogging along the way. I write what I learn, so I can revise it later and maybe help you avoid a few rabbit holes.