![CA 16 - [Leetcode] Guess the Number Higher or Lower](/_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%252Fl15hbqzr717hzeachdrl.png&w=1200&q=75)
CA 16 - [Leetcode] Guess the Number Higher or Lower
Problem We are playing a game where a number is picked from 1 to n. You need to guess the number using a predefined API guess(num): Returns -1 if your guess is higher than the picked number Returns 1 if your guess is lower than the picked number Returns 0 if your guess is correct The task is to return the picked number. Output Example 1 Output: 6 Example 2 Output: 1 Example 3 Output: 1 My Approach To solve this problem, I used Binary Search. I set two pointers: left = 1 right = n Then I repeatedly calculate the middle value: If guess(mid) == 0, I return mid If guess(mid) == -1, I move to the left half If guess(mid) == 1, I move to the right half I continue this process until I find the correct number. This works because the search space is reduced by half in every step. This approach is efficient because: It reduces the search space logarithmically It requires only constant extra space Code class Solution ( object ): def guessNumber ( self , n ): left = 1 right = n while left <= right
Continue reading on Dev.to
Opens in a new tab

