Guess Number Higher or Lower | LeetCode 374 | Python | Solution

Click here to see the problem on LeetCode.

This problem is all about Binary Search. If you know about Binary Search Algorithm, you can solve this problem.

In binary search, we search for a value from the mid. Generally, we know the searching value before starting the search. And based on that, we can decide where to search.

But here, we don’t know the value. For that, we have to call a pre-defined function (guess(num: int) -> int). And it takes an integer as a parameter. Based on the integer, it tells us whether our mid number is the searching value or not. If it’s not the searching value, it tells us where to search. Read the possible returns value of that functions from the problem description.

Let’s see the solution.

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        lower = 0
        higher = n
        while lower <= higher:
            mid = (lower + higher) // 2
            pick = guess(mid)
            if pick == 0:
                return mid
            elif pick == 1:
                lower = mid + 1
                higher = mid - 1

It’s a pretty easy Binary Search problem. It’s an implementation of the Binary Search Algorithm with a bit different approach. I hope you got the idea and solved it yourself.