Guess Number Higher or Lower
Introduction This problem is a classic example of using Binary Search to efficiently find a value within a given range. Instead of checking every number one by one, we reduce the search space by ha...

Source: DEV Community
Introduction This problem is a classic example of using Binary Search to efficiently find a value within a given range. Instead of checking every number one by one, we reduce the search space by half at each step. Problem Statement We are given a number between 1 and n. We need to guess the number using an API: guess(num) The API returns: -1 → Your guess is higher than the number 1 → Your guess is lower than the number 0 → Your guess is correct Our task is to find the correct number. Example 1: Input: n = 10, pick = 6 Output: 6 Key Idea Instead of guessing randomly, we use Binary Search: Start with the range 1 to n Pick the middle value Use the API result to decide: Search left half Or search right half Approach Initialize: low = 1 high = n While low <= high: Find middle: mid = (low + high) // 2 Call guess(mid) Based on result: 0 → return mid -1 → search left (high = mid - 1) 1 → search right (low = mid + 1) Python Implementation # The guess API is already defined # def guess(num):