PrepStack · Markdown HTML

Binary search on the answer

Binary search and monotone answer · HTML

Formal shape

For minimization, design can(x) as F…F T…T and find first True; for maximization, design T…T F…F and find last True.

Recognition signals

False friends

SignalWhy it is different
Nonmonotone feasibilityIf increasing x can switch success back to failure, binary search is invalid.
Huge domain with an expensive predicateApplicability does not imply speed; a direct greedy, heap, or selection method may dominate.

Core invariant

The closed interval [lo,hi] contains the optimum boundary; for first True, values left of lo are excluded and hi remains a feasible candidate.

State, transition, and processing order

ItemDefinition
StateSemantic lower bound lo, feasible upper bound hi, midpoint, and a can(mid) function answering only feasibility.
TransitionIf can(mid) is true, retain mid with hi=mid; otherwise set lo=mid+1.
Frontier / orderThe unresolved answer-value domain, halved only after a complete feasibility decision.

Python skeleton

def minimize_feasible(lo, hi, can):
    # Precondition: the optimum is in [lo, hi] and can(hi) is True.
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if can(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

Correctness sketch

  1. If mid is feasible, the minimum feasible value is at most mid, so retain the left half including mid.
  2. If mid is infeasible, monotonicity makes every smaller value infeasible as well, so exclude them together.
  3. The interval converges to a feasible value with no smaller feasible predecessor, exactly the optimum boundary.

Complexity

TimeSpaceParameters
O(C log W)O(S)W=hi-lo+1 is answer-domain width; one feasibility check costs time C and space S.

Edge cases

Error patterns

PatternWhy it fails / fix
Solving the full optimum inside canThe predicate should answer only whether the threshold suffices, remaining simple enough to prove monotone.
Searching in the wrong directionWrite the False/True picture before choosing which side feasibility retains.
Forgetting the log factorA cost-C predicate executes logarithmically many times.

Selection and exclusion rules

RelationTemplateBoundary
threshold-path alternativeMinimax / bottleneck DijkstraA bottleneck can be solved by ordered expansion or threshold search.
multi-query alternativeOffline activation with DSUMany can(t) checks would repeat graph searches
length-search compositionRolling hash / Rabin-KarpExistence of a repeated structure is monotone in length

Original micro-example

PartDetail
ResultThe first feasible capacity, 7, is the minimum answer.
SetupWork must finish within D days; guess daily capacity x and greedily check completion.
TraceEvery capacity below 7 fails and every capacity at least 7 succeeds; binary search calls only can(x).

Recall prompts

My notes