DEV Community

Mubashir
Mubashir

Posted on

Guess Number Higher or Lower

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:

  1. Start from the middle
  2. Initialize:
  3. low = 1
  4. high = n
  5. While low <= high:
  6. Find mid
  7. Call guess(mid)
  8. 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)