How I Understood Guess Number Higher or Lower (LeetCode 374)
When I first saw this problem, it looked like a classic guessing game.
The task is to find a number picked by an API using the minimum number of guesses.
At first, I thought about trying all numbers, but then I realized: binary search is perfect here.
** Problem**
You have a number n, and there is a hidden number pick between 1 and n.
The guess API works like this:
guess(num) returns:
-1 if num is higher than pick
1 if num is lower than pick
0 if num is exactly pick
You need to find the number using the API efficiently.
Example:
Python
n = 10, pick = 6
Output: 6
What I Noticed
Instead of guessing randomly, I can halve the search space every time:
If my guess is too high, look lower
If my guess is too low, look higher
This is exactly binary search logic.
What Helped Me
Breaking the problem into binary search steps made it simple:
Initialize low = 1 and high = n
While low <= high:
Take mid = low + (high - low) // 2
Call guess(mid)
If result is 0 → found the number
If result is -1 → adjust high = mid - 1
If result is 1 → adjust low = mid + 1
This guarantees we find the number in O(log n) guesses.
Code (Python)
Python
The guess API is already defined for you
def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
low = 1
high = n
while low <= high:
# Calculate middle point
mid = low + (high - low) // 2
res = guess(mid)
if res == 0:
# Found the number
return mid
elif res == -1:
# Guess is too high, look lower
high = mid - 1
else:
# Guess is too low, look higher
low = mid + 1
return -1
Example Usage
Python
Suppose the pick number is 6
solution = Solution()
print(solution.guessNumber(10))
Output:
Plain text
6
Complexity
Time: O(log n) — binary search halves the range each time
Space: O(1) — constant space, in-place logic
What I Learned
This problem is less about writing complex code and more about thinking algorithmically:
Binary search is perfect for searching in a range
Always adjust low and high based on feedback
Minimal number of guesses → efficient solution
** Final Thought**
At first, I thought this was a guessing game that might need trial-and-error.
Once I realized:
**** “I can halve the search space each time using binary search”
…it became straightforward and efficient.
This problem is a great example of algorithmic thinking over brute force.
Top comments (0)