Guess Number Higher or Lower
Problem Statement We are playing the Guess Game: I pick a number from 1 to n. You have to guess the number I picked. Each time you guess wrong, I tell you if my number is higher or lower than your ...

Source: DEV Community
Problem Statement We are playing the Guess Game: I pick a number from 1 to n. You have to guess the number I picked. Each time you guess wrong, I tell you if my number is higher or lower than your guess. You can call a pre-defined API: int guess(int num) It returns: -1 if your guess is higher than the number (i.e., num > pick) 1 if your guess is lower than the number (i.e., num < pick) 0 if your guess is correct (i.e., num == pick) Your task is to return the number I picked. Example 1: Input: n = 10, pick = 6 Output: 6 Example 2: Input: n = 1, pick = 1 Output: 1 Example 3: Input: n = 2, pick = 1 Output: 1 Constraints: 1 <= n <= 2^31 - 1 1 <= pick <= n Approach: Binary Search The most efficient way to guess the number is using binary search. Since the API tells us whether the pick is higher or lower, we can halve the search space with each guess. Steps: Start with a range [1, n]. Guess the middle number mid = left + (right - left) // 2. Call guess(mid): If it returns 0