704. Binary Search
Given a sorted array of distinct integers and a target, return its index, or -1 if it isn't present.
def search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
The textbook version. Compare the midpoint to the target, discard the half that can't contain it, repeat. The loop invariant -- the answer, if it exists, is always within [lo, hi] -- is the thing worth internalizing here.