The Guess Number Higher or Lower interview question is a classic game simulation. The system picks a secret number between 1 and n. You need to guess the number. If you guess wrong, an API guess(num) tells you whether your guess was too high (returns -1), too low (returns 1), or correct (returns 0). Your task is to find the secret number using the minimum number of guesses.
Companies like Google, Amazon, and Microsoft ask this coding problem as the foundational test of the Binary Search interview pattern. It evaluates whether a candidate understands the search space reduction technique. It’s an "Easy" difficulty question that focuses on basic control flow, variable updating, and avoiding integer overflow during midpoint calculation.
This problem is the textbook definition of Binary Search.
left = 1 and right = n.mid = left + (right - left) / 2.guess(mid).right = mid - 1.left = mid + 1.Suppose n = 10 and the secret number is 6.
left = 1, right = 10. mid = 5.guess(5) returns 1 (too low). Update left = 6.left = 6, right = 10. mid = 8.guess(8) returns -1 (too high). Update right = 7.left = 6, right = 7. mid = 6.guess(6) returns 0. Found!
Result: 6.(left + right) / 2. If left and right are near the maximum 32-bit integer limit, their sum will overflow, causing a crash. Always use left + (right - left) / 2.left or right past mid (e.g., using left = mid). This causes the search space to get stuck on a single element.1 and -1 returned by the guess API.Whenever you have a sorted or monotonic search space (numbers 1 to N are inherently sorted), Binary Search is the answer. Memorize the left + (right - left) / 2 overflow protection trick, as it's a common "gotcha" in interviews.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| First Bad Version | Easy | Solve | |
| Search in a Sorted Array of Unknown Size | Medium | Solve | |
| Find the Index of the Large Integer | Medium | Solve | |
| Number of Equal Numbers Blocks | Medium | Solve | |
| Find in Mountain Array | Hard | Solve |