Guess Number Higher or Lower
Problem
Given an integer n representing the range [1, n], return the number that matches the hidden target by using the guess API which returns -1, 1, or 0 indicating whether the guess is higher, lower, or correct.
- 1 ≤ n ≤ 2³¹ - 1
Example
n = 106Suppose the hidden target is 6. The algorithm starts with left=1 and right=10. It guesses mid=5, and guess(5) returns 1 (target is higher). It then moves left to 6. Next, it guesses mid=8, and guess(8) returns -1 (target is lower). It moves right to 7. Then it guesses mid=6, and guess(6) returns 0, indicating the correct number is found and returns 6.
Approach
Straightforward Solution
A naive approach would guess numbers sequentially from 1 to n, which is O(n) and inefficient for large n.
Core Observation
The problem is a classic search for a hidden number within a sorted range, where each guess narrows down the search space based on feedback. The fundamental truth is that the search space can be halved each time by comparing the guess to the target.
Path to Optimal
Recognizing the problem as a search in a sorted range with feedback indicating direction suggests binary search. By repeatedly guessing the midpoint and adjusting the search boundaries based on the guess API's response, the search space halves each iteration, leading to O(log n) time complexity.
Optimal Approach
Implement a binary search with two pointers, left and right, initialized to 1 and n. In each iteration, guess the midpoint. If the guess is correct, return it. If the guess is higher than the target, move the right pointer to mid - 1. If the guess is lower, move the left pointer to mid + 1. Continue until the correct number is found.
Time
O(log n)
Each guess halves the search space, so the number of guesses needed is proportional to the logarithm base 2 of n.
Space
O(1)
Only a fixed number of variables (left, right, mid, result) are used, regardless of input size.
Pattern Spotlight
Binary Search (Feedback-Guided Search)
When searching for a target in a sorted range with directional feedback, use binary search by halving the search space each iteration based on the feedback to achieve logarithmic time.
Solution
| 1 | class Solution: |
| 2 | def guessNumber(self, n: int) -> int: |
| 3 | left = 1 |
| 4 | right = n |
| 5 | |
| 6 | while left <= right: |
| 7 | mid = (left + right) // 2 |
| 8 | result = guess(mid) |
| 9 | |
| 10 | if result == 0: |
| 11 | return mid |
| 12 | elif result == -1: |
| 13 | right = mid - 1 |
| 14 | else: |
| 15 | left = mid + 1 |
Step-by-Step Solution
Initialize Search Boundaries to Cover the Entire Range
| 3 | left = 1 |
| 4 | right = n |
Objective
To set the initial search space boundaries to the full range from 1 to n.
Key Insight
Starting with left at 1 and right at n ensures the entire possible range of the target is considered. This setup is essential for binary search to function correctly, as it defines the initial search interval that will be halved iteratively.
Interview Quick-Check
Core Logic
Setting left=1 and right=n defines the initial search space for the binary search algorithm.
State & Boundaries
The search space is inclusive of both left and right pointers, so the loop condition must consider equality (left <= right).
Iteratively Narrow Search Space Using Midpoint Guesses
| 6 | while left <= right: |
| 7 | mid = (left + right) // 2 |
| 8 | result = guess(mid) |
| 10 | if result == 0: |
| 11 | return mid |
| 12 | elif result == -1: |
| 13 | right = mid - 1 |
| 14 | else: |
| 15 | left = mid + 1 |
Objective
To repeatedly guess the midpoint and adjust search boundaries based on feedback until the target is found.
Key Insight
Calculating the midpoint as the average of left and right pointers and using the guess API's feedback to move either the left or right pointer effectively halves the search space each iteration. This approach leverages the sorted nature of the search space and the directional feedback to efficiently converge on the target.
Interview Quick-Check
Core Logic
The binary search loop calculates mid, uses guess(mid) to get feedback, and moves left or right pointers accordingly to halve the search space.
State & Boundaries
The loop continues while left <= right to ensure all candidates are considered.
Common Pitfalls & Bugs
Calculating mid as (left + right) // 2 avoids overflow in languages without automatic big integer support.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
left = 1
Initialize the left boundary of the search space to 1.
Setting left to 1 ensures the search covers the entire valid range starting from the smallest possible target.
right = n
Initialize the right boundary of the search space to n.
Setting right to n ensures the search covers the entire valid range up to the largest possible target.
while left <= right:
Continue searching while the search space is valid (left <= right).
The loop condition ensures that the search space is not empty and all candidates are considered.
mid = (left + right) // 2
Calculate the midpoint of the current search space.
Midpoint calculation divides the search space in half, enabling efficient binary search.
result = guess(mid)
Call the guess API with the current midpoint.
The guess API provides directional feedback that guides the binary search narrowing.
if result == 0:
Check if the guess is correct (result == 0).
If the guess matches the target, the search terminates successfully.
return mid
Return the midpoint as the correct guess.
Returning mid immediately ends the search with the correct target.
elif result == -1:
Check if the guess is higher than the target (result == -1).
If the guess is too high, the search space must be reduced to the left half.
right = mid - 1
Move the right pointer to mid - 1 to narrow the search to the left half.
Adjusting right to mid - 1 eliminates all numbers greater than mid, focusing the search on smaller candidates.
else:
Otherwise, the guess is lower than the target (result == 1).
If the guess is too low, the search space must be reduced to the right half.
left = mid + 1
Move the left pointer to mid + 1 to narrow the search to the right half.
Adjusting left to mid + 1 eliminates all numbers less than mid, focusing the search on larger candidates.
Test Your Understanding
Why does moving the left or right pointer based on the guess API's feedback guarantee finding the target in O(log n) time?
Because each feedback narrows the search space by half, eliminating half of the remaining candidates, ensuring the target is found in logarithmic time relative to n.
Related Problems
Binary Search pattern
Don't just read it. Drill it.
Reconstruct Guess Number Higher or Lower from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Guess Number Higher or Lower drill