PrepStack · Markdown HTML

Binary-search boundary / first true

Binary search and monotone answer · HTML

Formal shape

Maintain closed [lo,hi] known to contain the answer. If mid is True, keep mid with hi=mid; otherwise exclude it with lo=mid+1, terminating at lo=hi.

Recognition signals

False friends

SignalWhy it is different
Any exact hitWhen no boundary is requested, ordinary exact binary search is clearer.
Nonmonotone predicateIf truth alternates, discarding half has no logical support.

Core invariant

The first True always lies in [lo,hi]; indexes left of lo are proven False, while hi remains a feasible candidate.

State, transition, and processing order

ItemDefinition
Statelo, hi, mid, and monotone predicate; this form assumes at least one True inside the interval.
TransitionIf predicate(mid) is True, set hi=mid; otherwise set lo=mid+1.
Frontier / orderThe closed interval of possible transition points; a True mid cannot be discarded because it may be the answer.

Python skeleton

def first_true(lo, hi, predicate):
    # Precondition: predicate(hi) is True.
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if predicate(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

Correctness sketch

  1. If mid is True, monotonicity only proves the answer is not to its right; mid itself can be first, so retain [lo,mid].
  2. If mid is False, mid and everything left are impossible first-True positions, so retain [mid+1,hi].
  3. The interval strictly shrinks to one point, and the invariant plus existence makes that point the first True.

Complexity

TimeSpaceParameters
O(log N) predicate callsO(1) beyond predicate spaceN=hi-lo+1; for predicate cost C, total time is O(C log N).

Edge cases

Error patterns

PatternWhy it fails / fix
Using hi=mid-1 on TrueThat discards a mid which may be the first True.
Mixing while lo<=hi with hi=midInconsistent interval semantics can create an infinite loop.
Assuming monotonicityA few friendly examples do not prove the predicate has only one transition.

Selection and exclusion rules

RelationTemplateBoundary
control-flow parentBinary search on the answercan(x) is exactly a first-True predicate.
accelerates predicatesPrefix sum / range aggregationBoundary checks repeatedly query range aggregates.
query compositionSparse table static RMQO(1) RMQ checks support boundary search
optimizationSubsequence dynamic programmingSome one-sequence increasing-length problems admit tails plus lower_bound.

Original micro-example

PartDetail
ResultThe interval converges to first-True index 3.
SetupAcross indexes 0..6 the predicate is F,F,F,T,T,T,T.
TraceAt 3 it is True, keep [0,3]; at 1 False, keep [2,3]; at 2 False.

Recall prompts

My notes