Summary - Binary Search
Types of Binary Search
Finding an exact target
loop condition: while left <= right
update pointers: left = mid + 1
and right = mid - 1
def binary_search(array, target):
left, right = 0, len(array) - 1 # Intial right is a possible value
while left <= right:
mid = (left + right) // 2
if array[mid] == target:
return mid # There is an additional if condition compared to other cases.
elif array[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Target not found
Example: Leetcode 374 Guess Number
Finding the lower bound
loop condition: while left < right
update pointers: left = mid + 1
and right = mid
def lower_bound(array, target):
left, right = 0, len(array) # Intial right is not a possible value
while left < right:
mid = (left + right) // 2
if array[mid] < target:
left = mid + 1
else:
right = mid
return left # This is the first of lower bound
Example: Leetcode 2300
Finding the upper bound
loop condition: while left < right
update pointers: left = mid + 1
and right = mid
def upper_bound(array, target):
left, right = 0, len(array) # Intial right is not a possible value
while left < right:
mid = (left + right) // 2
if array[mid] > target:
right = mid
else:
left = mid + 1
return left - 1 # This is the last of upper bound