Template - Find Minimum Valid

Template for finding the first value satisfying a condition.

Problem type: Find the minimum xx such that isValid(x) is true, where validity is monotonic (once true, stays true for larger xx).

function findMinValid(lo, hi):
    while lo < hi:
        mid = lo + (hi - lo) / 2
        if isValid(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

Invariant: hi is always a valid answer (or past the range). lo is the first potentially valid answer.

After loop: lo == hi is the minimum valid value.

Example uses:

  • Minimum speed to finish in time.
  • Minimum capacity to ship in days.
  • First version that is bad (git bisect).