In this task, I worked on guessing a number using a smart approach instead of checking every number one by one.
MY APPROACH
I created a function to guess a number between 1 and n using an API called guess(num).
The API returns:
-1 → my guess is higher than the picked number
- 1 → my guess is lower than the picked number
- 0 → my guess is correct
EXAMPLE :
Input : n = 10
pick = 6
output : 6
LOGIC IMPLEMENTED
Instead of checking all numbers, I used Binary Search:
- Start from the middle
- Initialize:
- low = 1
- high = n
- While low <= high:
- Find mid
- Call guess(mid)
- Adjust search range accordingly
class Solution:
def guessNumber(self, n):
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
Top comments (0)