Hi everyone!
Today I solved a fun problem based on a guessing game, and it turns out to be a perfect example of binary search.
Problem
We need to guess a number between 1 and n.
We are given an API:
-1 - guess is too high
1 - guess is too low
0 - correct guess
Our task is to find the correct number.
My Approach
At first, I thought of guessing numbers one by one (linear search), but that would be slow.
Then I realized:
Since the range is sorted (1 to n), we can use binary search.
Logic
Start with range low = 1 and high = n
Find middle value
Use guess(mid):
If correct - return mid
If too high - search left half
If too low - search right half
Code (Python)
class Solution:
def guessNumber(self, n: int) -> int:
low = 1
high = n
while low <= high:
mid = (low + high) // 2
res = guess(mid)
if res == 0:
return mid
elif res == -1:
high = mid - 1
else:
low = mid + 1
return -1
Time & Space Complexity
Time: O(log n)
Space: O(1)
Key Insight
Binary search reduces the search space by half each time, making it very efficient.
What I Learned
Binary search can be applied even without arrays
Always look for sorted patterns
This is a classic interview problem
Thanks for reading!
Feel free to share your thoughts or alternative approaches.
Top comments (0)