In this task, I worked on finding a hidden number within a given range using an efficient approach. Instead of checking every number one by one, I used binary search to reduce the number of guesses.
What I Did
I created a function guessNumber that tries to find a number between 1 and n.
There is a helper function called guess():
It returns 0 if the guess is correct
It returns -1 if the guessed number is too high
It returns 1 if the guessed number is too low
How I Solved It
I used two variables:
low starting from 1
high starting from n
Then I repeatedly found the middle value (mid) of the range.
At each step:
If the guess is correct, I return the number
If the guess is too high, I move the high pointer down
If the guess is too low, I move the low pointer up
This keeps reducing the search space until the correct number is found.
CODE:
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
How It Works
The function uses binary search, which divides the range into halves each time. Instead of checking all numbers, it quickly narrows down the possible range based on the result from the guess() function.
This makes the solution much faster compared to a linear search.
Top comments (0)