
Guess Number Higher or Lower - CA16
My Thinking and Approach Introduction In this problem, I was given a number range from 1 to n and asked to guess a number picked within this range. I can use a given API to check whether my guess is higher, lower, or equal to the picked number. Problem Statement A number is picked between 1 and n Use API guess(num) : Returns -1 → guess is higher Returns 1 → guess is lower Returns 0 → correct guess Find and return the picked number My Initial Thought At first, I considered: Checking each number one by one But this approach is slow for large values of n. Key Observation Instead of checking all numbers: I can reduce the search space Based on API response, eliminate half of the range Optimized Approach I decided to use Binary Search. Logic: If guess is too high → search left half If guess is too low → search right half Continue until correct number is found My Approach (Step-by-Step) Initialize: left = 1 right = n While left <= right: Find mid = (left + right) // 2 Call guess(mid): If resu
Continue reading on Dev.to Tutorial
Opens in a new tab



