PrepStack · Markdown HTML

Binary search on a sorted domain

Binary search and monotone answer · HTML

Formal shape

Maintain a closed interval [lo,hi] with the invariant: if target exists, it remains inside. Comparing a[mid] with target excludes one impossible side.

Recognition signals

False friends

SignalWhy it is different
First-true boundaryFor first or last occurrence, do not return on equality; preserve mid as a boundary candidate.
Binary search on answerWhen feasibility is monotone but input is unsorted, the search domain is answer values, not array positions.

Core invariant

At loop entry, an existing target lies inside closed interval [lo,hi]; every outside index has been disproved by sorted comparisons.

State, transition, and processing order

ItemDefinition
Statelo, hi, mid, and target; a closed interval is empty exactly when lo>hi.
TransitionIf a[mid]<target set lo=mid+1; if greater set hi=mid-1; return immediately on equality.
Frontier / orderThe contiguous interval of indexes not yet ruled out, rather than a queue or heap.

Python skeleton

def binary_search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Correctness sketch

  1. Sortedness proves that when a[mid]<target, mid and everything left cannot match; the symmetric case removes the right side.
  2. Each update excludes mid, so the interval strictly shrinks and the loop terminates.
  3. Equality is an immediate witness; if the interval empties without equality, the invariant proves absence.

Complexity

TimeSpaceParameters
O(log n)O(1)n is sequence length; every iteration removes at least half the remaining candidates.

Edge cases

Error patterns

PatternWhy it fails / fix
Using lo<hi with a closed intervalThe last candidate may never be examined; exact closed search uses lo<=hi.
Failing to exclude midUpdates lo=mid or hi=mid can loop forever on adjacent positions.
Blindly applying it to a rotated arrayThe whole array is not sorted; first identify which half is ordered.

Selection and exclusion rules

RelationTemplateBoundary
abstracts the search domainBinary search on the answerThe ordered object is feasibility over answer values.
built from exact searchBinary-search boundary / first trueAn ordered comparison is recast as a boundary predicate.
structural-analogyBST ordering / inorder traversalA BST comparison removes a subtree as array binary search removes an interval half.
also exploits orderOpposite-direction two pointersThe goal is pairwise squeezing rather than one-value lookup.

Original micro-example

PartDetail
ResultReturn index 3.
SetupFind 19 in sorted sequence [3,8,12,19,25].
Tracemid=2 gives 12, excluding the left half; new mid=3 matches.

Recall prompts

My notes