Binary Search in Action
Binary search is a topic that is easy to explain but hard to implement bug-free. Some example of the most common problems are:
- How to initialize the boundary
- When to exit the loop
- How to update the boundary, i.e. where to shrink
Boundary
The boundary is the range of elements we will be searching from. The initial boundary should include ALL the element.
int l = min(search_space), r = max(search_space)
For arrays, it looks:
int l = 0, r = nums.length - 1;
LeetCode 35 “Search Insert Position” asks to find an index to insert into the array. It is possible to insert after the last element of the array. Thus the boundary becomes:
int l = 0, r = nums.length;
Calculate mid
int mid = l + (r - l) / 2 // left/lower mid
int mid = l + (r - l + 1) / 2 // right/upper mid
int mid = r - (r - l) / 2 // right/upper mid
Templates
Template 1
l = min(search_space), r = max(search_space)
while l < r:
mid = l + (r - l) / 2 # left / lower
if checkOk(mid):
r = mid # right moves
else:
l = mid + 1
return l
Template 2
l = min(search_space), r = max(search_space)
while l < r:
mid = l + (r - l + 1) / 2 # right / upper
if checkOk(mid):
l = mid # left moves up
else:
r = mid - 1
return l
Steps
- Initialize the boundary to include all possible elements.
- Decide return value. After exiting the while loop, left is the minimal one satisfying the condition function.
- Design the condition function. This is the most difficult part and needs a lot of practice.
- Check [0, 1] and switch the mid calculation if needed, to avoid infinite loop.
LeetCode questions to practice
Easy
Medium
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array II
- Smallest Rectangle Enclosing Black Pixels
- Koko Eating Bananas
- Capacity To Ship Packages Within D Days
- Ugly Number III
- Find the Smallest Divisor Given a Threshold
- Minimum Number of Days to Make m Bouquets
Hard
- Split Array Largest Sum
- Maximum Average Subarray II
- Kth Smallest Number in Multiplication Table
- Find K-th Smallest Pair Distance
- Minimize Max Distance to Gas Station
- K-th Smallest Prime Fraction
- Find in Mountain Array
- Divide Chocolate