Coding Pattern:

Modified Binary Search

This pattern has a cheat sheet you can unlock.

Overview

Modified binary search finds the left-most or right-most occurrence of a target within a range.

There are three main types of binary search:
  • 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

Modified Binary Search Slide 1: Consider this question: Find the first index of our target, 8, in this sorted list. nums = [-3, 0, 0, 4, 8, 8, 9].
Modified Binary Search Slide 2: We could check every element in the list for the first 8. That takes O(n) time, since in the worst case we'd look at every element.
Modified Binary Search Slide 3: Binary search finds the 8 a lot faster. It works best on lists that are already sorted.
Modified Binary Search Slide 4: To start a binary search, we set low and high bounds to search between. Here the low bound is -3 at lo = 0, and the high bound is 9 at hi = 6.
Modified Binary Search Slide 5: We also keep a variable to track our result, starting at -1. We search half of the list over and over, and once lo passes hi, we return result.
Modified Binary Search Slide 6: Find the midway point with this equation: mid = (hi - lo) // 2 + lo. First take the difference between hi and lo...
Modified Binary Search Slide 7: Find the midway point with this equation: mid = (hi - lo) // 2 + lo. ...divide it by 2 and round down...
Modified Binary Search Slide 8: Find the midway point with this equation: mid = (hi - lo) // 2 + lo. ...then add lo to place it to the right of lo.
Modified Binary Search Slide 9: Or you can find the midpoint by averaging the two numbers: mid = (lo + hi) // 2. Use whichever one feels more natural to you.
Modified Binary Search Slide 10: Find the midway point: mid = (6 - 0) // 2 + 0 = 3. lo = 0, hi = 6, and result = -1.
Modified Binary Search Slide 11: If mid points at the target, we save it into result. Here it doesn't.
Modified Binary Search Slide 12: The value at mid (4) isn't the target. Our target (8) is greater than 4, so we search to the right of mid.
Modified Binary Search Slide 13: Move lo to the right of mid. The value at mid can't be the answer. We leave it out of the search. Now lo = 4 and hi = 6.
Modified Binary Search Slide 14: Cut the search in half again. The new midway point is mid = (6 - 4) // 2 + 4 = 5.
Modified Binary Search Slide 15: If mid points at the target, we save it into result. This time it does, so result = 5.
Modified Binary Search Slide 16: Our target (8) is at mid. If we only needed to know the target exists, we could stop here. To get the first occurrence, we keep searching to the left of mid.
Modified Binary Search Slide 17: Move hi to the left of mid. We already checked mid. We leave it out of the search. Now lo = 4 and hi = 4.
Modified Binary Search Slide 18: lo hasn't passed hi yet, so we keep searching. The new midway point is mid = (4 - 4) // 2 + 4 = 4.
Modified Binary Search Slide 19: If mid points at the target, we save it into result. It does, so result = 4.
Modified Binary Search Slide 20: mid points at the target. We keep searching to the left of mid, since we're still looking for the first occurrence.
Modified Binary Search Slide 21: Now hi = 3, so lo has passed hi. We stop searching and return result, which is 4.
Modified Binary Search Slide 22: What if we needed the LAST index of our target, 8? The algorithm is almost exactly the same.
Modified Binary Search Slide 23: We update result when mid points at the target. At mid = 5 it does, so result = 5.
Modified Binary Search Slide 24: But now when we find the target at mid, we search to the RIGHT of it, since we want the last occurrence.
Modified Binary Search Slide 25: lo hasn't passed hi, so we keep searching. The new midway point is mid = (6 - 6) // 2 + 6 = 6.
Modified Binary Search Slide 26: If mid points at the target, we save it into result. Here it doesn't.
Modified Binary Search Slide 27: The target isn't at mid. Our target (8) is less than the value at mid (9), so we search to the left of mid.
Modified Binary Search Slide 28: Move hi to the left of mid. We already checked mid. We leave it out of the search. Now hi = 5.
Modified Binary Search Slide 29: lo has passed hi, so we stop searching and return result, which is 5.
Modified Binary Search Slide 30: Each step cuts the search space in half. That's why binary search takes O(log₂n) = O(log n) time to find a target in a sorted list.
1 / 30

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)}")
main.py

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)}")
main.py

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 Initialization
    You 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 + lo

    or

    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 + 1 or hi = 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?

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).