15% off all plans & roadmaps Use code
See plansGuess Number Higher or Lower
- LeetCode 374
- Easy
- Binary Search Patterns
- On Sorted Array/List
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 - 11 <= 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.
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.
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
- Set
numto 1. - Call
guess(num)and read the reply. - If the reply is
0, returnnum. - Otherwise add 1 to
numand go back to the previous step. - Return -1 only if
numpassesn. 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
| Time | O(n) |
|---|---|
| Space | O(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
JavaTested in our runner
class Solution extends GuessGame {
public int guessNumber(int n) {
// Binary search: guess returns -1 when the pick is lower, 1 when it is higher
int lo = 1, hi = n;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int res = guess(mid);
if (res == 0) {
return mid;
}
if (res < 0) {
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return -1;
}
}C++Tested in our runner
class Solution {
public:
int guessNumber(int n) {
// Binary search: guess -1 means the pick is lower, 1 means higher
long long lo = 1, hi = n;
while (lo <= hi) {
long long mid = lo + (hi - lo) / 2;
int r = guess((int)mid);
if (r == 0) return (int)mid;
if (r < 0) hi = mid - 1;
else lo = mid + 1;
}
return -1;
}
};JavaScriptTested in our runner
var guessNumber = function(n) {
// Binary search: guess returns -1 when num is too high, 1 when too low
let lo = 1, hi = n;
while (lo <= hi) {
const mid = Math.floor(lo + (hi - lo) / 2);
const res = guess(mid);
if (res === 0) return mid;
if (res === -1) hi = mid - 1;
else lo = mid + 1;
}
return -1;
};GoTested in our runner
func guessNumber(n int) int {
// Binary search: guess returns -1 when the pick is lower than num, 1 when higher
lo, hi := 1, n
for lo <= hi {
mid := lo + (hi-lo)/2
switch guess(mid) {
case 0:
return mid
case -1:
hi = mid - 1
default:
lo = mid + 1
}
}
return -1
}C#Tested in our runner
public class Solution : GuessGame {
public int guessNumber(int n) {
// Binary search: guess returns -1 when num is above the pick, 1 when below
int lo = 1, hi = n;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int res = guess(mid);
if (res == 0) {
return mid;
}
if (res == -1) {
hi = mid - 1;
} else {
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 infographicSolution 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
- Set
leftto 1 andrightton. - While
leftis at mostright, computemid = left + (right - left) / 2. - Call
guess(mid)once and store the reply. - If the reply is
0, returnmid. - If the reply is
-1, the pick is belowmid, so setright = mid - 1. - If the reply is
1, the pick is abovemid, so setleft = mid + 1. - 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.
| Step | left | right | mid | guess(mid) | Update |
|---|---|---|---|---|---|
| 1 | 1 | 1000000 | 500000 | 1 | left = 500001 |
| 2 | 500001 | 1000000 | 750000 | -1 | right = 749999 |
| 3 | 500001 | 749999 | 625000 | -1 | right = 624999 |
| 4 | 500001 | 624999 | 562500 | -1 | right = 562499 |
| 5 | 500001 | 562499 | 531250 | 1 | left = 531251 |
| 6 | 531251 | 562499 | 546875 | -1 | right = 546874 |
| 7 | 531251 | 546874 | 539062 | 1 | left = 539063 |
| 8 | 539063 | 546874 | 542968 | 1 | left = 542969 |
| 9 | 542969 | 546874 | 544921 | -1 | right = 544920 |
| 10 | 542969 | 544920 | 543944 | -1 | right = 543943 |
| 11 | 542969 | 543943 | 543456 | -1 | right = 543455 |
| 12 | 542969 | 543455 | 543212 | -1 | right = 543211 |
| 13 | 542969 | 543211 | 543090 | 1 | left = 543091 |
| 14 | 543091 | 543211 | 543151 | 1 | left = 543152 |
| 15 | 543152 | 543211 | 543181 | 1 | left = 543182 |
| 16 | 543182 | 543211 | 543196 | 1 | left = 543197 |
| 17 | 543197 | 543211 | 543204 | 1 | left = 543205 |
| 18 | 543205 | 543211 | 543208 | 1 | left = 543209 |
| 19 | 543209 | 543211 | 543210 | 0 | return 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
| Time | O(log n) |
|---|---|
| Space | O(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 -1JavaTested in our runner
class Solution extends GuessGame {
public int guessNumber(int n) {
int left = 1;
int right = n;
while (left <= right) {
// Subtract first so left + right cannot overflow
int mid = left + (right - left) / 2;
int 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;
}
}C++Tested in our runner
class Solution {
public:
int guessNumber(int n) {
int left = 1;
int right = n;
while (left <= right) {
// Subtract first so left + right cannot overflow
int mid = left + (right - left) / 2;
int 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;
}
};JavaScriptTested in our runner
var guessNumber = function(n) {
let left = 1;
let right = n;
while (left <= right) {
// Math.floor keeps mid an integer
const mid = left + Math.floor((right - left) / 2);
const 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;
};GoTested in our runner
func guessNumber(n int) int {
left, right := 1, n
for left <= right {
// Subtract first so the sum cannot overflow
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
}C#Tested in our runner
public class Solution : GuessGame {
public int guessNumber(int n) {
int left = 1;
int right = n;
while (left <= right) {
// Subtract first so left + right cannot overflow
int mid = left + (right - left) / 2;
int 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 = midwhen the reply is1. With a two-number window,midequalsleft, so the window never shrinks and the loop repeats forever. Useleft = mid + 1.- Swapped branches, such as
if res == 1: right = mid - 1. A reply of1means the pick is higher, so this discards the answer. Send-1to the left side and1to the right side. mid = (left + right) / 2in Java or C++ with n near 2^31 - 1. The sum overflows a 32-bit int andmidturns negative. Useleft + (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 + rightoverflows 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, recordmidas a candidate and move the right bound tomid - 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
Related problems
- Binary Search · same technique: On Sorted Array/List
- Search Insert Position · same technique: On Sorted Array/List
- Sqrt(x) · same technique: On Sorted Array/List
- First Bad Version · same technique: On Sorted Array/List
- Kth Missing Positive Number · same technique: On Sorted Array/List
- Koko Eating Bananas · next harder, same pattern
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Find K Closest Elements · same pattern: Binary Search Patterns