Guess Number Higher or Lower solution explained

Guess Number Higher or Lower is plain binary search against a feedback function: guess the middle of the remaining range, and let the hint tell you which half to throw away. With numbers from 1 to n you need at most about log₂(n) + 1 guesses, so O(log n) time and O(1) space. The only real traps are the sign convention of the hint and computing the midpoint without overflow.

By Published 7 min read

The problem in plain words

Someone has picked a whole number from 1 to n. You cannot see it, but you can call a function, guess(x), that compares your guess with the hidden number. In the common version it returns -1 when your guess is too high (the hidden number is smaller), 1 when your guess is too low (the hidden number is bigger), and 0 when you hit it. Return the hidden number while calling the function as few times as you reasonably can.

A sample game, written for this page: n = 100, hidden number 73
Range beforeGuessguess() returnsRange after
1 to 100501 (too low)51 to 100
51 to 10075-1 (too high)51 to 74
51 to 74621 (too low)63 to 74
63 to 74681 (too low)69 to 74
69 to 74711 (too low)72 to 74
72 to 74730Found in 6 calls
A sample game, written for this page: n = 100, hidden number 73. Scroll sideways on a small screen.

Before coding, read the sign convention back to the interviewer in your own words. Some versions of this game define the return value from the hidden number's point of view and others from yours, and the code is identical except for which branch moves which bound.

Why such an easy problem gets asked

It isolates binary search from everything else. There is no array to index into and no sorted data to reason about, just a range and a comparison. That makes it a quick read on whether you can write a loop that terminates, keeps the answer inside its bounds, and does not overflow. Interviewers sometimes open with it and then move to a search over answers, such as finding the smallest capacity that meets a deadline, which reuses the exact same skeleton.

Slow approach: guess every number in order

Call guess(1), then guess(2), and so on until it returns 0. This always works and takes up to n calls. For n near two billion that is two billion calls, each possibly a network round trip in a real system. The linear version ignores most of the information each answer gives you, since a reply of 1 tells you about every number below your guess, not just the guess itself.

def guess_number_linear(n):
    for x in range(1, n + 1):
        if guess(x) == 0:
            return x
    return -1
Linear search: O(n) calls.

Main approach: halve the range with every call

Keep the hidden number inside [lo, hi], starting with 1 and n. Guess the midpoint. A reply of 0 ends the game. A reply saying your guess is too high means the number is below mid, so hi becomes mid - 1. A reply saying it is too low means the number is above mid, so lo becomes mid + 1. Each call removes at least half of the remaining candidates, so the range shrinks to one value within about log₂(n) steps.

def guess_number(n):
    lo, hi = 1, n
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        hint = guess(mid)
        if hint == 0:
            return mid
        if hint < 0:
            hi = mid - 1
        else:
            lo = mid + 1
    return -1
Python: O(log n) calls, O(1) space.
function guessNumber(n) {
  let lo = 1;
  let hi = n;
  while (lo <= hi) {
    const mid = lo + Math.floor((hi - lo) / 2);
    const hint = guess(mid);
    if (hint === 0) return mid;
    if (hint < 0) hi = mid - 1;
    else lo = mid + 1;
  }
  return -1;
}
JavaScript: the same loop. The -1 return only happens if the oracle is inconsistent.

Why lo + (hi - lo) / 2

In Java, C or C++ with 32-bit ints, lo + hi can exceed the largest int when both are above a billion, and the midpoint becomes negative. Writing lo + (hi - lo) / 2 keeps every intermediate value inside the range. Python integers grow as needed, and JavaScript doubles hold these sums exactly, so neither language needs it, but writing it anyway shows you know why it matters.

How many guesses, exactly

With the midpoint rule, the worst case is floor(log₂ n) + 1 calls. For n = 100 that is 7. For the largest 32-bit value it is 31. You cannot do better in the worst case with yes or no style feedback, because each call has three outcomes but two of them simply split the range, and the adversary can always steer you into the bigger half.

A common follow-up asks about ternary search: guess at one third and two thirds of the range. It removes two thirds of the candidates per round but uses two calls per round, which works out to more calls overall than halving. Saying that clearly is usually all the interviewer wants.

Complexity

n is the size of the range
ApproachAPI callsExtra spaceNote
Guess every numberO(n)O(1)Wastes the hint
Binary searchO(log n), at most floor(log₂ n) + 1O(1)The expected answer
Ternary searchO(log n) with a larger constantO(1)Worse than halving here
n is the size of the range. Scroll sideways on a small screen.

Edge cases to test

  • n = 1: the first guess is the answer.
  • The hidden number is 1 or n, the two ends of the range.
  • n at the 32-bit maximum, to exercise the midpoint formula.
  • The hidden number sits right next to the first midpoint, to check the plus and minus one updates.

Common mistakes

  • Reversing the sign convention, so a too-high guess raises lo instead of lowering hi. The search then drifts away and returns the wrong answer or loops.
  • Setting hi = mid or lo = mid instead of excluding mid, which can loop forever when lo and hi are adjacent.
  • Computing (lo + hi) / 2 in a 32-bit language.
  • Calling guess(mid) twice per iteration, once for each comparison. It doubles the calls and can matter if the oracle is expensive or rate limited.
  • Starting the range at 0 when the problem says 1.

How to explain it out loud

Fictional example

A thirty-second answer
Candidate
Let me confirm the hint: minus one means my guess was above the hidden number, plus one means it was below. Good.
Candidate
I keep the answer inside lo and hi, guess the midpoint, and drop the half the hint rules out, storing the hint so I only call once per step. That is logarithmic in n, at most 31 calls for a 32-bit range.
Candidate
I will write the midpoint as lo plus half the gap so it cannot overflow if this gets ported to Java.

Valid Perfect Square swaps the oracle for a squaring step but keeps the same loop. Arranging Coins searches for the largest value that still satisfies a condition, which adds a small twist to the exit. For binary search on an actual sorted list, see Find Smallest Letter Greater Than Target. The data structure interview questions page lists more search topics.

Using Natively while you prepare

Natively can look at a screenshot of a problem during practice and suggest the pattern behind it, which helps when you are building the habit of spotting a search over a range. Record a mock round with its transcription on your computer and you can later check that you confirmed the sign convention before you started typing. See an AI interview assistant for Mac and Windows.

Questions people ask

How do you solve Guess Number Higher or Lower?

Binary search on the range 1 to n. Guess the midpoint; if the hint says too high, set hi to mid - 1, if too low, set lo to mid + 1, and stop when the hint is 0.

How many guesses does binary search need?

At most floor(log₂ n) + 1. For n = 100 that is 7 guesses, and for the largest 32-bit value it is 31.

What does guess() return in this problem?

In the common version, -1 means your guess is higher than the hidden number, 1 means it is lower, and 0 means it is correct. Confirm the convention before coding, since flipping it breaks the search.

Is ternary search better for this problem?

No. It needs two calls per round to cut the range to a third, which adds up to more calls than halving with one call per round.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP