easyArrayBinary SearchBinary Search

Binary Search

easyTime: O(log n)Space: O(1)

Recognize the pattern

sorted arrayfind targetthe prompt wants you to keep cutting the search space down

Brute force idea

If you approach Binary Search in the most literal way possible, you get this: Linear scan. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

A calmer way to see Binary Search is this: Binary search: compare midpoint to target, halve the range. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Binary Search is this: At each step, the target must be in [left, right] — never eliminate the side containing it. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

The trap in Binary Search usually looks like this: Off-by-one in left/right bounds and the loop condition (use left <= right). When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Binary Search Pattern