374. Guess Number Higher or Lower - Detailed Explanation

A number between 1 and n has been picked. You may call a provided function guess(num), which returns -1 if your guess is too high, 1 if it is too low, and 0 if it is correct. Find the number in as few calls as possible. This is binary search stripped of everything else, which makes it a common phone screen opener.

It appears in the binary search section of LeetCode 75.

Examples

InputOutput
n = 10, pick = 66
n = 1, pick = 11
n = 2, pick = 11

Constraints

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

That upper bound is the entire reason this question is not trivial, and it is covered below.

Which pattern this problem belongs to

This is the modified binary search pattern. Ordinary binary search looks for a value in a sorted array by comparing against the midpoint. Here there is no array at all. The search space is the range of candidate answers from 1 to n, and the comparison comes from the guess function rather than from memory.

That shift matters well beyond this question. Once you can binary search a range of answers rather than a container, questions like Koko Eating Bananas become approachable, because they search a range of speeds using a feasibility test in place of a comparison.

Approach

Keep a low and a high bound, starting at 1 and n. Guess the midpoint. If the answer says too high, the pick is below the midpoint, so move high down. If it says too low, move low up. If it says zero, you are done. Each call halves the remaining range, so the number of calls is O(log n).

Two details decide whether the implementation is correct.

The midpoint must not overflow. With n up to 2^31 - 1, computing (low + high) / 2 in a language with 32-bit integers overflows and produces a negative midpoint. Write low + (high - low) / 2 instead, which never exceeds high. Python integers are arbitrary precision so the naive form works there, but the Java version must use the safe form and interviewers watch for it.

The sign convention is backwards from intuition. The API returns -1 when your guess is too high, not when it is too low. Reading it the other way inverts the search and loops forever. Say the convention out loud before writing the branch.

Python code

def guessNumber(n): """Binary search over the answer range. O(log n) calls, O(1) space.""" low, high = 1, n while low <= high: mid = low + (high - low) // 2 result = guess(mid) if result == 0: return mid if result < 0: # mid is too high, search lower high = mid - 1 else: # mid is too low, search higher low = mid + 1 return -1 # unreachable given the constraints

Java code

public int guessNumber(int n) { int low = 1, high = n; while (low <= high) { int mid = low + (high - low) / 2; // overflow safe int result = guess(mid); if (result == 0) return mid; if (result < 0) high = mid - 1; else low = mid + 1; } return -1; }

Complexity

MeasureValue
Calls to guessO(log n)
Extra spaceO(1)

At the maximum n, that is about 31 calls, which is a good concrete number to quote.

Common mistakes

  • Writing (low + high) / 2 in Java. It overflows at large n and produces a negative midpoint. The failing case is exactly the maximum allowed input, so it passes small tests and fails the real ones.
  • Inverting the sign. A return of -1 means your guess was too high. Getting this backwards gives an infinite loop rather than a wrong answer, which is harder to debug under time pressure.
  • Using low < high with the wrong update. Mixing a strict loop condition with high = mid - 1 can skip the answer. Pair low <= high with mid - 1 and mid + 1, which is the convention that is hardest to get wrong.
  • Calling guess more than once per iteration. Each call counts, so store the result in a variable and branch on it.
  • Find Peak Element, which binary searches without a sorted array by comparing neighbors.
  • Koko Eating Bananas, which binary searches a range of answers with a feasibility test.
  • First Bad Version, which is nearly the same question with a different API.

How to Prepare

  • Memorize the overflow-safe midpoint. Write low + (high - low) / 2 every time, in every language, so it is automatic.
  • Read the API contract aloud before coding. Most failures on this question are a misread sign, not a flawed algorithm.
  • Learn the answer-space variant. Binary searching a range rather than an array is the version that shows up in harder questions, and Grokking the Coding Interview teaches it as its own pattern. The short version is in the most common LeetCode patterns.
TAGS
Coding Interview Questions
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Which software skill is most in demand in USA?
How does Microsoft make hiring decision?
Which data structure is used for multithreading?
What are the strategies for debugging code under pressure?
What is critical thinking in software development?
What is the hardest question for AI?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
Discounted price for Your Region

$99

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
About Us
Our Team
Careers
Partners
Contact Us
Become Affiliate
Copyright © 2026 Design Gurus, LLC. All rights reserved.