DEV Community

Jonah Blessy
Jonah Blessy

Posted on

CA 16 - [Leetcode] Guess the Number Higher or Lower

Problem Statement: here

PS Goal:
A number is secretly picked between 1 and n. You can only call guess(num). It tells you:
-1 → your guess is too high
1 → your guess is too low
0 → correct answer
You have to guess the number.

Solution:
My initial thought while reading the problem statement was to narrow down the search using binary search algorithm since it eliminates half the possible values each iteration.

  • The logic is that when we guess a number less than the actual value, we can eliminate the values greater than our guess. The median value of 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)