codebrew.ai

Binary Search

Halve the range each step by comparing to the middle.

Approach

Keep [lo, hi] bounds and inspect the midpoint. If it equals the target you're done; if it's smaller search the right half, otherwise the left. Use lo + (hi − lo) / 2 for the midpoint and a consistent boundary convention to avoid infinite loops.

Time complexity

O(log n)

Space complexity

O(1)

Common mistake

Computing mid as (lo + hi) / 2 (can overflow) or mismatching the loop condition with how you update lo/hi.

See it run, step by step

Generate an interactive lesson for Binary Search — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Binary Search

Related problems