Problem Statement
We are playing the Guess Game:
I pick a number from 1 to n.
You have to guess the number I picked.
Each time you guess wrong, I tell you if my number is higher or lower than your guess.
You can call a pre-defined API:
int guess(int num)
It returns:
-1 if your guess is higher than the number (i.e., num > pick)
1 if your guess is lower than the number (i.e., num < pick)
0 if your guess is correct (i.e., num == pick)
Your task is to return the number 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 - 1
1 <= pick <= n
Approach: Binary Search
The most efficient way to guess the number is using binary search. Since the API tells us whether the pick is higher or lower, we can halve the search space with each guess.
Steps:
Start with a range [1, n].
Guess the middle number mid = left + (right - left) // 2.
Call guess(mid):
If it returns 0, we found the number.
If it returns -1, the pick is lower, so move right = mid - 1.
If it returns 1, the pick is higher, so move left = mid + 1.
Repeat until the correct number is found.
Python Solution
The guess API is already defined for you.
def guess(num: int) -> int:
Python Code
class Solution:
def guessNumber(self, n: int) -> int:
left, right = 1, n
while left <= right:
mid = left + (right - left) // 2
res = guess(mid)
if res == 0:
return mid # Correct guess
elif res < 0:
right = mid - 1 # Pick is lower than mid
else:
left = mid + 1 # Pick is higher than mid
Time Complexity: O(log n) β the search space is halved each step.
Space Complexity: O(1) β only a few pointers are used.
This method is concise, efficient, and ideal for very large numbers within the constraints. Itβs a classic example of binary search in real-world guessing problems.
United States
NORTH AMERICA
Related News

Open Harness: The Multi-Panel AI Powerhouse Revolutionizing Developer Workflows
8h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
7h ago
50% of Consumers Prefer Brands That Avoid GenAI Content
7h ago
CBS News Shutters Radio Service After Nearly a Century
7h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
7h ago