Search Target: 15s
lo<=hi for exact match (3 outcomes). lo<hi for boundary finding (2 outcomes, converges). Pick the right template.
BINARY SEARCH TEMPLATES — WHEN TO USE WHICH
────────────────────────────────────────────
TEMPLATE 1: lo <= hi (exact match)
lo, hi = 0, n - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target: return mid
elif a[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1 # not found
→ Use for: exact value search
→ Terminates: lo > hi (empty range)
TEMPLATE 2: lo < hi (converge to answer)
lo, hi = 0, n - 1
while lo < hi:
mid = (lo + hi) // 2
if condition(mid):
hi = mid # mid could be answer
else:
lo = mid + 1 # mid is not answer
return lo # lo == hi == answer
→ Use for: first/last position, min satisfying condition
→ Terminates: lo == hi (single candidate)
GOTCHA: use mid = (lo + hi + 1) // 2 when
lo = mid (not mid+1) to avoid infinite loop
Type it from memory. Go.