Guess the Number Higher or Lower [Leetcode]
Guess Number Higher or Lower Problem You’re playing a game where a number is picked between 1 and n. You have to guess it using an API that tells you: -1 → your guess is too high 1 → your guess is ...
![Guess the Number Higher or Lower [Leetcode]](https://media2.dev.to/dynamic/image/width=1200,height=627,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhviwaygd5g4selqq4h7c.png)
Source: DEV Community
Guess Number Higher or Lower Problem You’re playing a game where a number is picked between 1 and n. You have to guess it using an API that tells you: -1 → your guess is too high 1 → your guess is too low 0 → correct guess Strategy This is basically a classic binary search problem. Instead of searching an array, you’re searching a range from 1 to n. At each step: Pick the middle number Use the API to check Narrow the range based on the response Code class Solution: def guessNumber(self, 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 Key Lines Explained mid = (left + right) // 2 Choose the middle of the current range. res = guess(mid) Ask whether the guess is correct, too high, or too low. res == -1 Means the guess is too high → move left. res == 1 Means the guess is too low → move right. Why This Works Each guess eliminates half of the remaining range. So instead of c