Binary Search Master Recap — All Patterns & Templates

Sanjeev SharmaSanjeev Sharma
4 min read

Advertisement

Binary Search — Master Recap

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


The 7 Core Patterns

#PatternWhenlo/hi init
1Classic Exactsorted, find exact0, n-1; lo<=hi
2Left Boundaryfirst True position0, n; lo<hi; hi=mid
3Right Boundarylast True position0, n; lo<hi; upper mid
4Rotated Arraycheck which half sorted0, n-1
5BS on Answerminimize/maximize feasibleanswer range
62D Matrixtreat as 1D0, m*n-1
7Peak Findingeliminate downhill0, n-1; lo<hi

The Universal Template

# Left boundary (minimize) — first index where condition holds
lo, hi = lower_bound, upper_bound  # inclusive
while lo < hi:
    mid = lo + (hi - lo) // 2
    if condition(mid):
        hi = mid       # answer could be mid or left
    else:
        lo = mid + 1   # answer must be right of mid
return lo
# Right boundary (maximize) — last index where condition holds
lo, hi = lower_bound, upper_bound
while lo < hi:
    mid = lo + (hi - lo + 1) // 2  # upper mid prevents infinite loop
    if condition(mid):
        lo = mid       # answer could be mid or right
    else:
        hi = mid - 1   # answer must be left of mid
return lo

BS on Answer Cheatsheet

Problemlohifeasible(mid)direction
Koko Eating1max(piles)total_hours <= hminimize: hi=mid
Ship Packagesmax(w)sum(w)days_used <= dminimize: hi=mid
Magnetic Force1(max-min)/(m-1)count_with_gap >= mmaximize: lo=mid
Split Arraymax(arr)sum(arr)parts <= kminimize: hi=mid
Cutting Ribbons1max(r)total_cuts >= kmaximize: lo=mid
Min Speed11e7total_time <= hourminimize: hi=mid

Rotated Array Patterns

# Search target
if nums[lo] <= nums[mid]:  # left sorted
    if nums[lo] <= target < nums[mid]: hi=mid-1
    else: lo=mid+1
else:  # right sorted
    if nums[mid] < target <= nums[hi]: lo=mid+1
    else: hi=mid-1

# Find minimum
if nums[mid] > nums[hi]: lo=mid+1  # min in right
elif nums[mid] < nums[hi]: hi=mid  # min in left or mid
else: hi-=1  # duplicates: safe shrink

Big O Reference

ProblemTimeSpacePattern
Classic Binary SearchO(log n)O(1)Classic
Find First/LastO(log n)O(1)Left+Right boundary
Rotated ArrayO(log n)O(1)Half-sort check
Koko EatingO(n log m)O(1)BS on Answer
LIS PatienceO(n log n)O(n)Patience + bisect
Median Two ArraysO(log min(m,n))O(1)Partition
Kth in Sorted MatrixO(n log V)O(1)BS on Value
Count Range SumO(n log n)O(n)Merge Sort

Common Pitfalls

  1. Overflow: use mid = lo + (hi-lo)//2, not (lo+hi)//2
  2. Infinite loop: right-boundary template needs upper mid (lo+hi+1)//2
  3. hi init: for insert position use hi = n (not n-1)
  4. Rotated with dups: when nums[lo]==nums[mid], do lo++ (can't determine sorted half)
  5. BS on Answer — feasible direction: minimize → if feasible: hi=mid; maximize → if feasible: lo=mid
  6. Circular search: return letters[lo % n] to wrap around

MAANG Interview Priority

Must-Know:

  • Binary Search (classic + both boundaries)
  • Search in Rotated Array I & II
  • Find Minimum in Rotated Array
  • Koko Eating Bananas (BS on Answer)
  • LIS with patience sort
  • Median of Two Sorted Arrays

High Value:

  • Kth Smallest in Sorted Matrix
  • Split Array Largest Sum
  • Count of Range Sum (merge sort)
  • Russian Doll Envelopes (2D LIS)

Next Section → Trees (problems 346–420)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro