Binary Search
Use when: searching in a sorted space, or when the answer space is monotonic (if X works, X-1 also works).
Signal words: sorted array, find minimum/maximum that satisfies condition, O(log n) required.
Core Idea
Reframe as: minimize k such that condition(k) is True.
Template (generalized)
def binary_search(arr):
def condition(value) -> bool:
pass # define your condition
left, right = 0, len(arr) # set boundary to include all candidates
while left < right:
mid = left + (right - left) // 2
if condition(mid):
right = mid # mid could be answer, shrink right
else:
left = mid + 1 # mid definitely not answer, move left up
return left # left == right == first index where condition is TrueSetup Checklist
- What is the search space? (index range, value range, answer range)
- What is the condition? (monotonic - once true, stays true)
- Return
leftorleft - 1? (left= first True,left - 1= last False)
Common Variants
- Search in rotated sorted array: check which half is sorted first
- Binary search on answer: search the value space, not index space