← Search

Micro-Drill #244 — Binary search: lo<=hi vs lo<hi

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 &lt;= hi (exact match)
  lo, hi = 0, n - 1
  while lo &lt;= hi:
      mid = (lo + hi) // 2
      if a[mid] == target: return mid
      elif a[mid] &lt; target: lo = mid + 1
      else: hi = mid - 1
  return -1  # not found
  → Use for: exact value search
  → Terminates: lo &gt; hi (empty range)

TEMPLATE 2: lo &lt; hi (converge to answer)
  lo, hi = 0, n - 1
  while lo &lt; 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.

Practice Problems

Related Coding Drills

← Micro #243 Micro #245 →