searchBinary Search

Binary Search: when to spot it, explain it, and practice it

Binary search is really about exploiting monotonicity. The strongest candidates stop thinking about arrays only and start thinking about predicates that flip from false to true.

Pattern coverage

40+

Best first move

Define the predicate before choosing loop bounds.

Common failure point

Using the wrong interval convention and causing infinite loops.

When this pattern should come to mind

You can define a predicate that changes only once across the search space.
The problem asks for a first valid, last valid, minimum feasible, or maximum feasible value.
A linear scan would work but feels too slow against the input size.

Checklist before you code

Define the predicate before choosing loop bounds.
Decide whether the right boundary is inclusive or exclusive.
Keep one invariant for the false side and one for the true side.
Return the boundary, not the last mid you saw.

The solving flow that works well in interviews

1

Write the monotonic predicate in plain English first.

2

Choose a search interval that definitely contains the answer.

3

Use mid to test feasibility, not to guess blindly.

4

Move one boundary and preserve the invariant every time.

5

Return the boundary that represents the first feasible or last infeasible point.

Common variants

Exact match

The classic sorted-array search for a target.

Boundary search

Find the first or last position satisfying a condition.

Answer-space search

Binary search on capacity, speed, or some feasible answer rather than an array index.

Template preview

PythonPublic preview
# Find first position where check(mid) is true
left, right = 0, n
while left < right:
    mid = left + (right - left) // 2
    if check(mid):
        right = mid
    else:
        left = mid + 1
return left

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Using the wrong interval convention and causing infinite loops.

warning

Returning mid instead of the boundary.

warning

Failing to prove monotonicity before starting.

warning

Overflow or off-by-one issues when computing mid and boundaries.

Recommended practice path

1

Start with boundary problems such as first/last position.

2

Then solve rotated-array and peak-style questions.

3

After that, move to answer-space problems like shipping capacity and minimum speed.

4

Review exact-match binary search last so boundary intuition stays dominant.

Binary Search Pattern Guide | LeetCode Interview Prep - Interview AiBox