![Guess the Number Higher or Lower [Leetcode]](/_next/image?url=https%3A%2F%2Fmedia2.dev.to%2Fdynamic%2Fimage%2Fwidth%3D1200%2Cheight%3D627%2Cfit%3Dcover%2Cgravity%3Dauto%2Cformat%3Dauto%2Fhttps%253A%252F%252Fdev-to-uploads.s3.amazonaws.com%252Fuploads%252Farticles%252Fhviwaygd5g4selqq4h7c.png&w=1200&q=75)
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 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.
Continue reading on Dev.to Python
Opens in a new tab

