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...
![CA 16 - [Leetcode] Guess the Number Higher or Lower](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%2Fl15hbqzr717hzeachdrl.png)
Source: DEV Community
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: mid