progress

~/problems / Binary search / Binary search on the answer

Smallest value that passes a check

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Binary search on the answer has one skeleton: a monotone yes/no check ok(x) (false, ..., false, true, ...) and you want the first true. Write it once, as a helper.

Write first_true(lo: int, hi: int, ok) -> int that returns the smallest x in [lo, hi] with ok(x) true. ok(hi) is always True.

first_true(0, 100, lambda x: x * x >= 50)   # 8   (7*7 = 49 is not enough)
first_true(1, 10, lambda x: True)            # 1   (true everywhere: the answer is lo)
first_true(5, 5, lambda x: True)             # 5

The range can be 10^18 wide, and the tests count your calls: about log2(hi - lo + 1) + 2 are allowed, so scanning upward is out.

Show hint

keep "the answer is in [lo, hi]": if ok(mid) then hi = mid, else lo = mid + 1.

Topic: Binary search on the answer. Monotonic feasibility check + search the smallest value that works.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc