15% off all plans & roadmaps Use code

See plans

Guess Number Higher or Lower

Updated

TL;DR: You must find a hidden number from 1 to n using a guess API that says higher or lower. Binary search halves the range on each guess, so it needs at most about 31 calls for the largest n instead of up to n.

Problem

We are playing a guessing game. I pick a number from 1 to n, and you have to guess which number I picked.

Every time you guess wrong, I tell you whether my number is higher or lower than your guess. You call the pre-defined API int guess(int num), which returns one of three results:

  • -1: your guess is higher than my number (num > pick).
  • 1: your guess is lower than my number (num < pick).
  • 0: your guess equals my number (num == pick).

Return the number that I picked.

Example 1

Input: n = 10, pick = 6
Output: 6

Example 2

Input: n = 1, pick = 1
Output: 1

Example 3

Input: n = 2, pick = 1
Output: 1

Constraints

  • 1 <= n <= 2^31 - 1
  • 1 <= pick <= n

Constraints that matter

  • n up to 2^31 - 1 rules out the linear scan. About 2 billion calls is far too many, so each call must cut the candidate range by a constant factor.
  • The pick always lies inside 1 to n. That guarantees the window never empties before a reply of 0, so the loop can rely on it.
  • The API only returns -1, 0, or 1. The branch on each reply must match the API's meaning, and flipping the sign is the most common error.
  • Values near 2^31 - 1 can overflow a 32-bit integer when added. The midpoint must subtract before it adds.

View on LeetCode

Hints

Hint 1

This is binary search on a sorted range.

Hint 2

The most literal solution asks about every number in order, starting at 1, until the API returns 0.

Solution

Intuition

This is binary search on a sorted range. The candidates 1 through n are already in order, and each reply from guess tells you which side of your guess the answer lies on. That is the signal binary search needs: a cheap test that discards a whole side of the remaining candidates.

Picture searching a paper dictionary for one word. The page you open is mid, and the pages still in your hands are the window from left to right, so each reply tears away the half that cannot hold the word.

Notice how much a single wrong guess removes. A reply of -1 means your guess is too high, so the pick is below mid, and the window can end at mid - 1. A reply of 1 means the pick is above mid, so the window can start at mid + 1. Either way you drop the guess and an entire half.

The method stays correct because of one invariant. The pick always stays inside the window [left, right]. Each call cuts the window roughly in half, so it shrinks toward the pick, and the call that returns 0 ends the search.

A linear scan ignores this structure. It asks about one number at a time and never uses the direction of the reply. Spotting the sorted range and the directional feedback tells you to switch to binary search.

Watch the pattern animation

Worked example

Input: n = 1000000, pick = 543210
Output: 543210
Explanation: The pick sits in the upper part of the range. The search halves the window 19 times, guessing 543210 on the last call, which returns 0. The brute force scan would need 543210 calls for the same answer.

Approach 1: Brute force

The most literal solution asks about every number in order, starting at 1, until the API returns 0. It never uses the higher or lower reply, so it is correct, but a guess only rules out the one number you tested. The window stays as large as it was at the start.

It always finishes, because the pick is in [1, n]. The cost depends on where the pick sits. If the pick is n, you make n calls, which is about 2 billion for the largest allowed input. The API becomes the bottleneck long before the loop ends.

Steps

  1. Set num to 1.
  2. Call guess(num) and read the reply.
  3. If the reply is 0, return num.
  4. Otherwise add 1 to num and go back to the previous step.
  5. Return -1 only if num passes n. Valid input never reaches this line.

Dry run

Here the pick is 543210. The loop calls guess(1), which returns 1 because 1 is lower than the pick. It repeats that for 2, 3, and every number up to 543209. Each of those calls returns 1.

Then guess(543210) returns 0, and the function returns 543210. The scan made 543210 calls to reach the answer, and the output matches the example.

Complexity

TimeO(n)
SpaceO(1)

Let n be the range size. The loop runs once for each value from 1 up to the pick, so it makes at most n calls to guess. Only num and the reply are stored, so the extra space stays constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def guessNumber(self, n: int) -> int:
        # Binary search: guess returns -1 if pick is lower, 1 if higher, 0 if equal
        lo, hi = 1, n
        while lo <= hi:
            mid = lo + (hi - lo) // 2
            res = guess(mid)
            if res == 0:
                return mid
            if res < 0:
                # pick is lower than mid
                hi = mid - 1
            else:
                # pick is higher than mid
                lo = mid + 1
        return -1

The On Sorted Array/List infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

On Sorted Array/List

Part of Binary Search Patterns

Approach 2: Binary search on the windowOptimalOn Sorted Array/List

What's slow: the brute force ignores the reply and moves up one number at a time, so a pick near n costs n calls. Each reply already says which side holds the pick, and the scan wastes that signal.

The insight that fixes it: test the middle of the window instead of its edge. A reply of 1 discards mid and everything below it. A reply of -1 discards mid and everything above it. Each call therefore removes about half of what remains.

Steps

  1. Set left to 1 and right to n.
  2. While left is at most right, compute mid = left + (right - left) / 2.
  3. Call guess(mid) once and store the reply.
  4. If the reply is 0, return mid.
  5. If the reply is -1, the pick is below mid, so set right = mid - 1.
  6. If the reply is 1, the pick is above mid, so set left = mid + 1.
  7. If the loop ends without a 0, return -1. Valid input never reaches this line.

Dry run

The table below uses n = 1000000 and pick = 543210. Each row shows the window before the guess, the midpoint, the reply, and the update.

Stepleftrightmidguess(mid)Update
1110000005000001left = 500001
25000011000000750000-1right = 749999
3500001749999625000-1right = 624999
4500001624999562500-1right = 562499
55000015624995312501left = 531251
6531251562499546875-1right = 546874
75312515468745390621left = 539063
85390635468745429681left = 542969
9542969546874544921-1right = 544920
10542969544920543944-1right = 543943
11542969543943543456-1right = 543455
12542969543455543212-1right = 543211
135429695432115430901left = 543091
145430915432115431511left = 543152
155431525432115431811left = 543182
165431825432115431961left = 543197
175431975432115432041left = 543205
185432055432115432081left = 543209
195432095432115432100return 543210

The window starts with 1000000 numbers. After step 18 it holds only three numbers, and step 19 hits the pick. The search made 19 calls, against 543210 for the scan, and it returns 543210 as the example expects.

Complexity

TimeO(log n)
SpaceO(1)

Let n be the range size. Each iteration removes mid and one side, so the remaining window is at most half the old one. After k iterations at most n / 2^k values remain, and the loop stops once the window is empty.

That gives at most floor(log2 n) + 1 iterations, which is 31 for n = 2^31 - 1. Each iteration keeps a fixed set of integers, so the space is O(1).

PythonTested in our runner

class Solution:
    def guessNumber(self, n: int) -> int:
        left, right = 1, n
        while left <= right:
            # Subtract before adding so the formula stays safe in fixed-width languages
            mid = left + (right - left) // 2
            res = guess(mid)
            if res == 0:
                return mid
            if res == -1:
                # The guess is too high, so the pick is below mid
                right = mid - 1
            else:
                # The guess is too low, so the pick is above mid
                left = mid + 1
        return -1

Common mistakes

  • left = mid when the reply is 1. With a two-number window, mid equals left, so the window never shrinks and the loop repeats forever. Use left = mid + 1.
  • Swapped branches, such as if res == 1: right = mid - 1. A reply of 1 means the pick is higher, so this discards the answer. Send -1 to the left side and 1 to the right side.
  • mid = (left + right) / 2 in Java or C++ with n near 2^31 - 1. The sum overflows a 32-bit int and mid turns negative. Use left + (right - left) / 2.
  • if guess(mid): in Python. Both -1 and 1 are truthy, so the code returns on a wrong guess. Compare the reply with == 0.
  • Calling guess(mid) more than once in one iteration, for example once in the test and again in a branch. Each extra call wastes an API call and can hide the reply you meant to use. Store the reply in a variable and branch on it.

Edge cases

  • n = 1: the window is [1, 1]. The first guess must return 0, so the function returns 1 after one call.
  • n = 2 with pick = 1: guess(1) returns 0 at once. With pick = 2, guess(1) returns 1, the window becomes [2, 2], and the search returns 2.
  • n = 3 with pick = 3: the first midpoint is 2 and returns 1. The next window is [3, 3], so the second midpoint returns 3.
  • pick = 1 or pick = n with a large n: both ends take about log2 n calls. The search does not favour either end of the range.
  • n = 2^31 - 1 with pick = n: left + right overflows a 32-bit int, so the midpoint must subtract first. The search still returns n in about 31 calls.

Follow-ups interviewers ask

What if n can be as large as 10^18?
The logic does not change. Use 64-bit integers for left, right, and mid, and keep the form that subtracts before it adds. log2(10^18) is about 60, so the search needs at most about 60 calls.
Can you write it recursively?
Yes. The function takes left and right, guesses the middle, and calls itself on the half that can still hold the pick. The recursion depth is about log2 n, which is about 31 for the largest input. The loop version uses O(1) space and avoids the call stack, so I would write that first.
How does this change if you need the first value where a check becomes true, as in First Bad Version?
The window and midpoint logic stay the same. When the check is true at mid, record mid as a candidate and move the right bound to mid - 1, so the search looks for an earlier true value. The stopping rule changes, but the halving idea does not.

Guess Number Higher or Lower FAQ

What is the time complexity of Guess Number Higher or Lower?

The binary search version makes O(log n) calls to guess, at most about 31 for n = 2^31 - 1. The linear scan makes O(n) calls, which is too many for the largest input. Both versions use O(1) extra space.

Why use binary search for Guess Number Higher or Lower?

The candidates are the sorted integers from 1 to n, and each reply says which side holds the pick. Each reply can discard about half of the window, so binary search finds the pick in logarithmic calls.

Can Guess Number Higher or Lower be solved in O(1) extra space?

Yes. The iterative version stores left, right, mid, and the reply, which is a fixed amount of memory. A recursive version uses O(log n) stack frames, so prefer the loop when space matters.

Can you do fewer than log2 n guess calls in the worst case?

No. A reply other than 0 rules out the guess and one whole side, so about half the candidates can go per call. An adversary can keep the remaining candidates large for about log2 n calls, so the bound is tight.

Do I need to worry about overflow in Python?

Python integers have no fixed size, so left + right cannot overflow. Keep the left + (right - left) // 2 form anyway, because Java, C++, C#, and Go do overflow on 32-bit ints.

Asked at

See which companies ask this — Pro

Practise it