Guess Number Higher or Lower
EasyPrompt
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
-1: Your guess is higher than the number I picked (i.e.num > pick).1: Your guess is lower than the number I picked (i.e.num < pick).0: your guess is equal to the number I picked (i.e.num == pick).
Return the number that I picked.
Example 1:
Input: n = 10, pick = 6
Output: 6Example 2:
Input: n = 1, pick = 1
Output: 1Example 3:
Input: n = 2, pick = 1
Output: 1
Constraints:
1 <= n <= 231 - 11 <= pick <= n
Approaches
2 approaches with complexity analysis and trade-offs.
This approach involves checking every number sequentially from 1 up to n. We call the guess() API for each number until we find the correct one.
Algorithm
-
- Iterate through numbers from
i = 1ton.
- Iterate through numbers from
-
- For each number
i, call theguess(i)API.
- For each number
-
- If
guess(i)returns0, it meansiis the correct number. Returni.
- If
-
- If the loop finishes, it means the number was not found (this case is not possible according to the problem constraints).
Walkthrough
We start by guessing the number 1. We then call the guess(1) API. If it returns 0, we've found the number. If not, we proceed to guess 2, then 3, and so on, until we reach n. This method is straightforward but very slow, as it might require up to n calls to the guess() API in the worst case.
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * 0 if num is equal to the picked number * public int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n) { for (int i = 1; i <= n; i++) { if (guess(i) == 0) { return i; } } return -1; // Should not be reached based on problem constraints }}Complexity
Time
O(n) - In the worst-case scenario, we might have to iterate through all the numbers from 1 to n.
Space
O(1) - We only use a constant amount of extra space for variables.
Trade-offs
Pros
Simple to understand and implement.
Cons
Highly inefficient for large values of
n.Will result in a 'Time Limit Exceeded' error on most coding platforms due to the
nconstraint being up to2^31 - 1.
This is the optimal approach. It works by maintaining a range of possible numbers [low, high] and repeatedly guessing the middle number. Based on the API's feedback, we eliminate half of the range in each step, drastically reducing the search time.
Algorithm
-
- Initialize two pointers,
low = 1andhigh = n.
- Initialize two pointers,
-
- Loop as long as
low <= high.
- Loop as long as
-
- Calculate the middle index:
mid = low + (high - low) / 2.
- Calculate the middle index:
-
- Call the
guess(mid)API.
- Call the
-
- If the result is
0, returnmid.
- If the result is
-
- If the result is
-1(guess is too high), it means the target is in the lower half, so updatehigh = mid - 1.
- If the result is
-
- If the result is
1(guess is too low), it means the target is in the upper half, so updatelow = mid + 1.
- If the result is
Walkthrough
We initialize two pointers, low to 1 and high to n, which define our search space. In each step of the loop, we calculate the middle point mid. It's calculated as low + (high - low) / 2 to avoid potential integer overflow when low and high are large. We then call guess(mid).
- If
guess(mid)returns 0, we've found the number and can returnmid. - If
guess(mid)returns -1 (our guess is too high), we know the picked number must be in the lower half, so we updatehigh = mid - 1. - If
guess(mid)returns 1 (our guess is too low), the picked number must be in the upper half, so we updatelow = mid + 1. We repeat this process untillowis no longer less than or equal tohigh, at which point we will have found the number.
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * 0 if num is equal to the picked number * public int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n) { int low = 1; int high = n; while (low <= high) { // Using (low + high) / 2 might cause overflow for large n int mid = low + (high - low) / 2; int result = guess(mid); if (result == 0) { return mid; } else if (result == -1) { // My guess is higher than the picked number high = mid - 1; } else { // My guess is lower than the picked number low = mid + 1; } } return -1; // Should not be reached }}Complexity
Time
O(log n) - With each guess, we eliminate half of the remaining search space, leading to logarithmic time complexity.
Space
O(1) - We only use a constant amount of extra space for pointers and the middle value.
Trade-offs
Pros
Extremely efficient and optimal for this problem.
Handles large values of
neasily within time limits.
Cons
Slightly more complex to conceptualize than a linear scan, but it's a fundamental algorithm.
Solutions
Solution
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * int guess(int num); */ public class Solution : GuessGame { public int GuessNumber ( int n ) { int left = 1 , right = n ; while ( left < right ) { int mid = left + (( right - left ) >> 1 ); if ( guess ( mid ) <= 0 ) { right = mid ; } else { left = mid + 1 ; } } return left ; } }/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * int guess(int num); */ public class Solution extends GuessGame { public int guessNumber ( int n ) { int left = 1 , right = n ; while ( left < right ) { int mid = ( left + right ) >>> 1 ; if ( guess ( mid ) <= 0 ) { right = mid ; } else { left = mid + 1 ; } } return left ; } }/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * int guess(int num); */ class Solution { public: int guessNumber ( int n ) { int left = 1 , right = n ; while ( left < right ) { int mid = left + (( right - left ) >> 1 ); if ( guess ( mid ) <= 0 ) { right = mid ; } else { left = mid + 1 ; } } return left ; } };# The guess API is already defined for you. # @param num, your guess # @return -1 if num is higher than the picked number # 1 if num is lower than the picked number # otherwise return 0 # def guess(num: int) -> int: class Solution : def guessNumber ( self , n : int ) -> int : return bisect . bisect ( range ( 1 , n + 1 ), 0 , key = lambda x : - guess ( x ))Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.