Modified Binary Search
Overview
Modified binary search finds the left-most or right-most occurrence of a target within a range.
- List-Based Binary Search: This is the most common type. You're asked to find the left-most or right-most occurrence of something in a list. The list is usually sorted.
- Range-Based Binary Search: This one comes up less often. You get a range of numbers to search, like -10 to 100. You'll usually need to write a function that checks each guess.
- Tree-Based Binary Search: This walks down a binary search tree to find a target. You usually won't be asked to implement it. It's more of a data structure than an algorithm.
Note
You'll probably need binary search when a question asks you to find something in a sorted list.
This pattern focuses on list-based binary search and range-based binary search.
Pattern concept
Use ← → arrow keys
Solution templates
List-Based Binary Search
def list_binary_search(nums: List[int], target: int) -> int:
# Variable Initialization
lo, hi = 0, len(nums) - 1
result = -1
# Binary Search Initialization
while lo <= hi: # Stop searching after lo passes hi.
mid = (hi - lo) // 2 + lo # Find the midway point.
# Validation
if nums[mid] == target:
result = mid
# Search
if nums[mid] == target:
# The target is equal to mid.
# A) To only find the target, STOP here.
# break
# B) To find the LEFT-MOST occurrence, continue LEFT:
hi = mid - 1
# C) To find the RIGHT-MOST occurrence, continue RIGHT:
# lo = mid + 1
elif target < nums[mid]:
# Since the target is less than the value at mid,
# then the target should be on the left side.
hi = mid - 1
else:
# Since the target is greater than the value at mid,
# then the target should be on the right side.
lo = mid + 1
return result
arr = [-3, 0, 0, 4, 8, 8, 9]
print(f"The left-most occurrence of 8 is at index: {list_binary_search(arr, 8)}")
Range-Based Binary Search
def is_less_than_or_equal_to_secret(n: int) -> bool:
"""
Returns True if n is less than or equal to a secret number.
"""
SECRET_NUMBER = 1255;
if n <= SECRET_NUMBER:
return True
return False
def range_binary_search(left: int, right: int) -> int:
# Variable Initialization
lo, hi = left, right
result = None
# Binary Search Initialization
while lo <= hi: # Stop searching after lo passes hi.
mid = (hi - lo) // 2 + lo # Find the midway point.
# Validation
if is_less_than_or_equal_to_secret(mid):
result = mid
# Continue searching since there might be
# a bigger number that returns true!
# Search
if is_less_than_or_equal_to_secret(mid):
# Since mid is smaller than the secret number,
# the secret number should be on the right side.
lo = mid + 1
else:
# Since mid is greater than the secret number,
# the secret number should be on the left side.
hi = mid - 1
return result
print(f"The secret number is: {range_binary_search(0, 10000)}")
Binary search is easy to get wrong because of all its edge cases. We wrote the templates above to be easy to reason through.
Note
You'll find plenty of other ways to write binary search online. This is just one opinionated version. Use whichever version you're most comfortable with.
There are 4 main steps in solving a binary search problem:
- Variable InitializationYou always need these variables:
- lo: The left-most index of the range.
- hi: The right-most index of the range.
Note
We use inclusive array indexing. That means the values at lo and hi are part of the search.
- nums: The list you're searching. It's usually given to you. Sometimes you need to build it or sort it yourself.
- result: The result of the search. Start it at None or -1. If it still has that value when the search ends, the target wasn't found.
- Binary Search Initialization
Keep searching as long as lo has not passed hi. In other words, keep going while
lo <= hi.Each round starts by finding the midpoint of the range. These two formulas give the same answer. Use whichever one you like:
mid = (hi - lo) // 2 + loor
mid = (hi + lo) // 2 - Validation
Check whether mid is the target. If you only need to know that the target exists, you can stop the loop right there.
If you need the left-most or right-most occurrence, keep searching.
- Search
Decide which half of the list to keep searching. Then move lo or hi to that side.
Remember to skip over the index you just checked. Both lo and hi are inclusive.
Example:lo = mid + 1orhi = mid - 1.Note
This is the hardest part of binary search. It's worth slowing down here.
How to identify
Does the problem involve any of these?
- Searching for the left-most (earliest/first/minimum) occurrence of a target within a range
- First Bad Version: Search for the earliest/left-most bad version.
- Search in Rotated Sorted List: Search for the first/left-most target when half the list is sorted.
- Capacity to Transfer Packages: Search for the minimum/left-most capacity of baskets that can carry all packages.
- Searching for the right-most (latest/last/maximum) occurrence of a target within a range
- First and Last Positions in a Sorted List: Search for the first/left-most and last/right-most positions of a target.
- Maximum Count of Positives or Negatives: Search for the last/right-most negative integer and first/left-most positive integer.
Each step removes half of the remaining range from the search. When the list doubles in size, you only need one more step.
That means binary search takes O(log₂n) steps. People usually write that as O(log n).