Binary Search
& Answer Space

Applying monotonic logic to efficiently narrow down search spaces.

What This Pattern Is Really About

delete_foreverElimination Logic

Binary search is not about finding an element; it is about discarding half the search space. Every decision permanently eliminates a range of impossible candidates.

call_splitDecision Framework

It is a mechanism to convert a search problem into a series of Yes/No questions. If you can define a monotonic predicate, you can search anything.

data_arrayArray Context

In arrays, indices represent the search space. The sorted property guarantees that checking a midpoint validates or invalidates an entire half.

question_answerAnswer Space

Often the answer is not in an array but in a range of values (e.g., time, capacity). If the validity function is monotonic, the answer itself can be binary searched.

Mental Model & Invariant

Search domains must be ordered. If index i satisfies a condition, then either all indices >i or all indices <i must also satisfy (or fail) that condition.

This monotonicity allows checking a single midpoint to make a valid claim about half the entire domain.

The Core Invariant
If the answer exists, it must lie within the current [low, high] range.

Every update to low or high must preserve this truth.

verified

Monotonic Feasibility

The predicate function (isValid, isPossible) must switch from False to True (or vice-versa) exactly once across the domain.

gavel

Search Space Definition

Whether array indices [0, n-1] or numerical range [min, max], the boundaries must cover all possible valid answers.

When to Think "Binary Search"

network_checkStrong Signals

check

Input array is already sorted

check

Searching for a value in a monotonic range

check

Finding the first or last occurrence of a value

check

Accessing index is O(1) random access

check

Maximizing or minimizing a value constrained by a function

timerConstraint Signals

speed

O(log N) time complexity required

speed

N is large (e.g., 10^5 or greater)

speed

Input too large to iterate linearly

speed

Memory limit prevents auxiliary data structures

speed

Simple linear scan results in Time Limit Exceeded

Binary Search Variants You Must Master

Classic Binary Search

Purpose

Find exact index of target in sorted array.

Invariant

"Target is in [low, high] if it exists."

Intent

Lookup existence or index.

First / Last Occurrence

Purpose

Find boundaries of duplicate elements.

Invariant

"All values < target are left; all > target are right."

Intent

Counting frequencies or range boundaries.

Answer Space Search

Purpose

Find min/max value satisfying a condition.

Invariant

"Range [L, R] contains the optimal valid answer."

Intent

Optimization problems where answer is monotonic.

Capacity / Allocation

Purpose

Determine min capacity to handle workload.

Invariant

"If capacity K works, K+1 works too."

Intent

Load balancing, shipping, cutting items.

Search on Real Numbers

Purpose

Find root or value with decimal precision.

Invariant

"Root lies within [L, R] error margin."

Intent

Geometry, physics, or continuous mathematical functions.

How to Learn Binary Search Properly

1

Identify Monotonicity

Before searching, define the property that allows elimination. Is the array sorted? Does the answer space go from False -> True?

2

Define the Feasibility Function

Isolate the logic that checks a single candidate value. Create a `check(x)` function that returns a boolean.

3

Establish the Invariant

Decide whether your answer is in [L, R] or (L, R]. Stick to one convention for all problems to build muscle memory.

4

Handle Termination & Boundaries

Determine if the loop ends when L == R or L > R. Verify strict inequalities to prevent infinite loops.

5

Trace Edge Cases Manually

Walk through arrays of size 0, 1, and 2. Ensure your termination logic holds without off-by-one errors.

Canonical Problem List

Solving hundreds of problems isn't necessary. These cover the distinctive monotonic patterns; others are just flavor text on the same logic.

Common Mistakes

warning

Infinite Loops (mid selection)

The Error

Left-biased mid `(L+R)/2` combined with `L = mid` causes infinite loops on 2-element arrays.

The Fix

Use `mid = (L+R+1)/2` for right-bias if updating `L = mid`.

warning

Integer Overflow

The Error

Calculating `(L+R)/2` exceeds max integer limit when indices are large.

The Fix

Use `L + (R-L)/2` to prevent overflow.

warning

Off-by-One (L < R vs L <= R)

The Error

Mismatched loop condition and update logic leaves one element unchecked or causes infinite loop.

The Fix

If update excludes mid (`L=mid+1`), use `L <= R`. If update keeps mid (`R=mid`), use `L < R`.

warning

Applying to Unsorted Data

The Error

No monotonic property exists, so elimination logic is invalid.

The Fix

Sort the data first or verify a rotated/mountain property exists.

warning

Premature Optimization of Range

The Error

Trying to tighten [L, R] bounds manually often misses valid answers.

The Fix

Start with a safe, wide range (e.g., [0, max_val]) and let the algorithm narrow it.

Interview Guidance

Interview Protocol

What they test

  • Boundary correctness (L < R vs L ≤ R)
  • Identifying hidden monotonicity
  • Handling integer overflow
  • Defining search space accurately

The Insight

The key isn't writing the loop—it's proving the problem is monotonic. If you can explain why `check(x)` allows you to discard half the universe, the implementation is just a formality.

The Verbal Template

Search Space

"The answer lies between [min_possible, max_possible]."

Monotonicity

"The `check(x)` function is monotonic: if X works, all values >X (or <X) also work."

Elimination

"Therefore, I'll test `mid`. If `check(mid)` is true, I can safely discard the [left/right] half."

Conclusion

"This reduces the search space logarithmically to find the boundary."

When You've Mastered This Pattern

check_circle

Can define search space instantly

check_circle

Writes L <= R or L < R without guessing

check_circle

Spots monotonicity in 'unsorted' problems

check_circle

Never writes infinite loops

check_circle

Applies to non-integer domains (time, real numbers)

check_circle

Explains 'why' before writing 'while'

What This Unlocks Next

account_tree

Segment Trees

Binary search applied to range query data structures.

timeline

Two Pointers

Linear elimination logic often combined with binary search.

functions

Newton's Method

Faster convergence on continuous functions using derivatives.

mediation

Ternary Search

Finding optima in unimodal functions by dividing into three parts.

"If you can define a monotonic Yes/No question, you can find the answer in logarithmic time. That is a superpower."