DEV Community

Jonah Blessy
Jonah Blessy

Posted on • Edited on

Guess the Number Higher or Lower

Problem Statement: here

PS Goal:
A number is secretly picked between 1 and n. We can only call guess(num). Possible outputs are -1,0,1. -1 means our guess is too high. 1 means our guess is too low. 0 means we got the correct answer. We have to guess the number.

Solution:

  • After reading the problem statement i instantly thought of using binary search algorithm. Because we have to guess a number and with the output we will know if our guess is higher or lower than the number. So we can cut the search in half using binary search.
  • So when we guess a number less than the actual value, we can eliminate the values greater than our guess. The middle value between actual value and our guess is the mid value.
  • Similar iteration is done when our guess is greater than the actual value.
  • The iteration stops when we find the number.
def guessNumber(n):
    left, right = 1, n
    while left <= right:
        mid = (left + right) // 2
        res = guess(mid)
        if res == 0:
            return mid
        elif res == -1:
            right = mid - 1
        else:
            left = mid + 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)