3.1 Binary Search (1D, 2D & Answer Space)
Understand what Binary Search is, why cutting a search space in half turns 1 billion steps into 30, and master Exact, Rotated, and Answer-Space Binary Search.
1. What Is Binary Search?
Binary Search is a divide-and-conquer search algorithm that finds a target inside a sorted (or monotonic) collection by repeatedly checking the middle element (mid) and throwing away the entire half where the target cannot possibly be.
2. Why Do We Need Binary Search & How Does It Work?
The Pain of Linear Search (O(N)) vs. Halving (O(log N))
Suppose you have a sorted array of 1,000,000,000 (1 billion) items:
- Linear Search (
forloop): Checks items one by one from index0. Worst case: 1,000,000,000 steps. - Binary Search: Checks the middle (
500,000,000). With one comparison (<or>), it eliminates 500 million items! After 30 halvings (2^30 > 10^9), only 1 item is left. Worst case: 30 steps (O(log N))!
The 3 Core Binary Search Scenarios
- Standard & Boundary Search: Finding an exact number (
while left <= right) or finding the first index wherenums[i] >= target(while left < right).
| Binary Search Style | Loop Condition | When nums[mid] Matches / Works | Best Used For |
|---|---|---|---|
| Exact Match | while left <= right: | return mid immediately | Finding a specific target value when all elements are distinct |
Lower Bound (first >= target) | while left < right: | right = mid (keep mid and look left!) | Finding the first occurrence of a duplicate or minimum feasible speed/capacity |
Upper Bound (first > target) | while left < right: | right = mid when nums[mid] > target | Counting how many elements are <= target |
- Rotated Sorted Arrays: When
[0, 1, 2, 4, 5, 6, 7]is rotated into[4, 5, 6, 7, 0, 1, 2], at least one half ([left..mid]or[mid..right]) is still strictly sorted. Check which half is sorted, test iftargetlies inside that half's endpoints, and narrow the range!
- Binary Search on Answer Space (
Koko Eating Bananas): Even when there is no sorted array given, if a question asks "What is the minimum speed/capacityXneeded to finish a task?", notice thatcan_finish(X)is monotonic: if speedXis too slow (False), every slower speed is alsoFalse; once speedXworks (True), every faster speed also works (True)!
Step Through the Visual Drawing: Halving the Search Space
Click Next below to trace how Binary Search locates 23 by discarding half the array on every comparison:
Interactive Step-by-Step Trace: Binary Search Halving
Find target = 23 in sorted [2, 5, 8, 12, 16, 23, 38] by cutting the array in half:
12 is smaller than 23. Since the array is sorted, everything left of 12 is also too small!
3. Basic Operations & Walkthroughs (All 4 Languages)
# 1. Standard Exact Match Binary Search -> O(log N)
def binary_search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# 2. First True / Lower Bound Template -> O(log N)
def first_feasible(min_ans: int, max_ans: int, can_finish) -> int:
left, right = min_ans, max_ans
while left < right:
mid = left + (right - left) // 2
if can_finish(mid):
right = mid # mid works! Keep it and try smaller
else:
left = mid + 1 # mid failed! Must go higher
return left4. Core Interview Patterns & Common Traps
Use whenever the problem asks for the minimum X (or maximum X) such that a condition can_finish(X) is True, and can_finish(X) flips monotonically from False to True.
left, right = min_possible, max_possible
while left < right:
mid = left + (right - left) // 2
if can_finish(mid):
right = mid # mid works! Keep mid and try smaller
else:
left = mid + 1 # mid is too small! Must go higher
return left| Operation / Pattern | Time | Space | Notes |
|---|---|---|---|
| 1D Binary Search (Exact / Lower Bound) | O(log N) | O(1) | Halves search range each step |
| 2D Sorted Matrix Search | O(log(R * C)) | O(1) | Treat as 1D array of size R*C: row = mid // C, col = mid % C |
| Binary Search on Answer Space | O(N log M) | O(1) | M = max_ans - min_ans; O(N) per feasibility check |
5. Practice On Your Own (Curated Submodule Problems)
| Status | Problem | Difficulty | Complexity | Hint? | Links & Notes |
|---|---|---|---|---|---|
Binary Search Standard & Boundary Binary Search | Easy | T: O(log N) S: O(1) | |||
Search a 2D Matrix Standard & Boundary Binary Search | Medium | T: O(log(R * C)) S: O(1) | |||
Search in Rotated Sorted Array Rotated & Peak Array Search | Medium | T: O(log N) S: O(1) | |||
Find Minimum in Rotated Sorted Array Rotated & Peak Array Search | Medium | T: O(log N) S: O(1) | |||
Koko Eating Bananas Binary Search on Answer Space | Medium | T: O(N log M) S: O(1) |