DEV Community

Luckshvadhan B
Luckshvadhan B

Posted on

Guess the Number Higher or Lower

Approach:
Step 1 Take range from 1 to n
Step 2 Use binary search
Step 3 Find mid value
Step 4 Call guess(mid)
Step 5 If 0 return mid
Step 6 If -1 search left
Step 7 If 1 search right

Why this works???
Each time we remove half of range
so faster than checking one by one

Code:
def guessNumber(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

Limitation:
Depends on given guess API

Top comments (0)