← Binary Search

Pattern Recognition Drill

#51 — Binary search template

Easy Binary Search

The Problem

Given a sorted array and a target value, return the index of the target or -1 if not found.

What approach would you use?

Think about it before scrolling down.

Key Signals

Binary Search

lo=0, hi=n-1. Compare mid. If target < mid, search left; if target > mid, search right. O(log n).

Common Trap

Watch the off-by-one: lo <= hi (not lo < hi). And mid = lo + (hi-lo)//2 avoids overflow.

← #50 #52 →