Binary Search
š§ Spot It
Use Binary Search when:
- Input is sorted (array, range, search space)
- Problem asks for a specific value, or min/max that satisfies a condition
- Brute force is O(N) or O(N²) ā binary search brings it to O(log N)
Key insight: Binary search isn't just for sorted arrays ā it's a search space reduction tool.
Pattern 1 ā Classic Binary Search
Find a target in a sorted array.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2 # avoid overflow
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Pattern 2 ā Find Boundary (leftmost / rightmost)
Used when duplicates exist or you need first/last occurrence.
def find_left_boundary(arr, target):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
result = mid
right = mid - 1 # keep searching left
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
Pattern 3 ā Binary Search on Answer (Search Space)
Problem gives a range of possible answers ā binary search the answer space.
Template:
def binary_search_answer(lo, hi):
result = -1
while lo <= hi:
mid = lo + (hi - lo) // 2
if is_feasible(mid): # define your condition
result = mid
hi = mid - 1 # or lo = mid + 1 depending on min/max
else:
lo = mid + 1
return result
Classic example: Koko Eating Bananas ā binary search on eating speed, check if feasible.
Senior Tricks
mid = left + (right - left) // 2ā never(left + right) // 2(overflow risk in other langs)- Rotated sorted array ā check which half is sorted, then decide which way to search
bisectmodule in Python:bisect_left,bisect_rightfor production code
Problems
| # | Problem | Pattern | Link | Status |
|---|---|---|---|---|
| 1 | Binary Search | Classic | LC 704 | |
| 2 | Search a 2D Matrix | Classic | LC 74 | |
| 3 | Find Minimum in Rotated Sorted Array | Rotated | LC 153 | |
| 4 | Search in Rotated Sorted Array | Rotated | LC 33 | |
| 5 | Time Based Key-Value Store | Boundary | LC 981 | |
| 6 | Koko Eating Bananas | Search Space | LC 875 | |
| 7 | Median of Two Sorted Arrays | Hard | LC 4 |