◀ THE GRIND — BINARY SEARCH

Guess Number Higher Or Lower

The drill: Guess a secret number between 1 and n using only higher/lower feedback from a black-box API — this write-up adapts that API into a plain pick parameter so the search itself can be verified offline. Minimize calls by halving the range each guess.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A secret number between 1 and n has already been chosen, and the drill is to identify it using only a black-box comparison — adapted on this site as a pick value passed alongside n so the search can be checked without a live API.

Each guess against that hidden pick returns one of three signals: the guess was too low, too high, or exactly right. Nothing else about the secret number is ever revealed directly.

The goal is to land on the correct number using as few guesses as possible, stopping the moment the exact-match signal comes back.

EX 01
n = 10 · pick = 6
6
SMALL RANGE, MID-ISH PICK
EX 02
n = 1 · pick = 1
1
MINIMUM SIZE, ONLY CHOICE
EX 03
n = 2 · pick = 1
1
TWO NUMBERS, LOWER ONE
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Each guess gives one of three answers — too high, too low, or correct — which is exactly the three-way comparison binary search already makes.

HINT 2 THE STRUCTURE

Treat [1, n] as the search window and use the API's answer the same way you'd compare against a midpoint in an array you could see directly.

HINT 3 ONE STEP FROM THE ANSWER

Guess the midpoint, shrink the window based on the response, and stop the moment it says correct — this is binary search with the comparison outsourced to guess().

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE RANGE GUESSPATTERN · BINARY SEARCH ON THE RANGEn = 10 · pick = 6
1
2
3
4
5
6
7
8
9
10
STEP 1

The secret number is somewhere in 1 through 10. Each guess only says higher or lower — binary search the range.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/guess-number-higher-or-lower.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def guess(self, num: int) -> int:
        if num > self.pick:
            return -1
        if num < self.pick:
            return 1
        return 0

    def guessNumber(self, n: int, pick: int) -> int:
        self.pick = pick
        lo, hi = 1, n
        while lo <= hi:
            mid = (lo + hi) // 2
            res = self.guess(mid)
            if res == 0:
                return mid
            elif res < 0:
                hi = mid - 1
            else:
                lo = mid + 1
        return -1
TIME O(LOG N)SPACE O(1)PYTHON · RACE PACE · 21 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED