progress

~/problems / Binary search / Binary search

Guess the number

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

A number secret is hidden somewhere in 1 .. n. You play the halving strategy: always guess the middle of the range that's still possible, mid = (lo + hi) // 2. If mid is too low, the range becomes mid + 1 .. hi; if it's too high, lo .. mid - 1. You stop when you guess right.

Write guesses(n: int, secret: int) -> list[int] that returns your guesses in order, ending with secret.

guesses(10, 7)   # [5, 8, 6, 7]   5 low, 8 high, 6 low, then 7
guesses(10, 5)   # [5]
guesses(1, 1)    # [1]

Constraints: 1 <= secret <= n <= 10^18. Halving needs at most 60 guesses even then.

Show hint

lo and hi are the smallest and largest numbers still possible. Every wrong guess throws away mid and everything on the wrong side of it.

Topic: Binary search. lo/hi invariants, lower vs upper bound, rotated arrays, bisect.

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