Binary Search — Complete Guide: All Patterns & Problem Index

Sanjeev SharmaSanjeev Sharma
5 min read

Advertisement

Binary Search — Complete Pattern Guide

Problems 301–345 · 45 posts · Easy × 8, Medium × 27, Hard × 10


Core Patterns

#PatternConditionExample
1Classic — Exact Targetnums[mid] == targetBinary Search, Search in Matrix
2Left Boundary (first true)lo = mid+1 when condition falseFirst Bad Version, Find First/Last
3Right Boundary (last true)hi = mid-1 when condition trueFloor/Ceiling, Find Closest
4Rotated ArrayCheck which half is sortedSearch Rotated Array
5BS on AnswerBinary search on result spaceKoko Eating Bananas, Capacity Ships
62D MatrixTreat as 1D arraySearch a 2D Matrix
7Peak FindingEliminate downhill halvesFind Peak Element

The Universal Template

# Left boundary (first index where condition is True)
def binary_search(lo, hi):
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if condition(mid):
            hi = mid       # answer could be mid
        else:
            lo = mid + 1   # answer is after mid
    return lo  # lo == hi == first True position
# Right boundary (last index where condition is True)
def binary_search_right(lo, hi):
    while lo < hi:
        mid = lo + (hi - lo + 1) // 2  # upper mid to avoid infinite loop
        if condition(mid):
            lo = mid       # answer could be mid
        else:
            hi = mid - 1   # answer is before mid
    return lo

Avoid Integer Overflow

Always use mid = lo + (hi - lo) // 2 instead of (lo + hi) // 2.


BS on Answer Template

def bs_on_answer(lo, hi):
    # lo = min possible answer, hi = max possible answer
    while lo < hi:
        mid = (lo + hi) // 2
        if feasible(mid):  # can we achieve 'mid'?
            hi = mid       # try smaller (minimize)
        else:
            lo = mid + 1   # need larger
    return lo

Easy (301–308)

#ProblemPattern
301Binary SearchClassic Exact
302First Bad VersionLeft Boundary
303Search Insert PositionLeft Boundary
304Guess Number Higher or LowerClassic
305Sqrt(x)Right Boundary
306Count Negative Numbers in Sorted MatrixRow Binary Search
307Check If N and Its Double ExistClassic
308Valid Perfect SquareClassic / Math

Medium (309–335)

#ProblemPattern
309Find First and Last PositionLeft+Right Boundary
310Search in Rotated Sorted ArrayRotated
311Find Minimum in Rotated Sorted ArrayRotated (min)
312Search a 2D Matrix2D as 1D
313Search a 2D Matrix IIStaircase Search
314Koko Eating BananasBS on Answer
315Minimum Number of Days to Make BouquetsBS on Answer
316Find Smallest Letter Greater Than TargetCircular BS
317Capacity to Ship PackagesBS on Answer
318Split Array Largest SumBS on Answer
319Find Peak ElementPeak BS
320Find K Closest ElementsBS + Expand
321Random Pick with WeightPrefix Sum + BS
322Magnetic Force Between Two BallsBS on Answer
323Missing Element in Sorted ArrayBS on Gap
324Time Based Key-Value StoreBS on sorted times
325Successful Pairs of Spells and PotionsSort + BS
326Maximum Value at a Given IndexBS on Answer
327Single Element in Sorted ArrayParity BS
328Find the Duplicate Number (BS)BS on count
329Longest Increasing Subsequence (Patience)BS patience sort
330H-Index IILeft Boundary
331Online ElectionBS on sorted times
332Search in Rotated Sorted Array IIRotated with dups
333Count of Range SumBS / Merge Sort
334Minimize Maximum of ArrayBS on Answer
335Kth Smallest in Sorted MatrixBS on Value

Hard (336–345)

#ProblemPattern
336Find Minimum in Rotated Array IIRotated with dups
337Median of Two Sorted ArraysBS on partition
338Count Smaller Numbers After SelfMerge Sort / BIT
339Minimum Number of Days to DisconnectBS + Connectivity
340Russian Doll Envelopes2D LIS + BS
341Split Array Largest Sum (Hard)BS on Answer
342Aggressive CowsBS on Answer
343K-th Smallest Prime FractionBS on Value
344Cutting RibbonsBS on Answer
345Binary Search Master RecapCheatsheet

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro