Problem Description
We need to guess the number picked by the system (via the guess API) from the range 1 to n. The API returns whether our guess is higher, lower, or exactly the pick. Our task is to find the correct number.
Key Insights
- The problem can be effectively solved using binary search since the search space is sorted by nature (1 to n).
- Each API call helps to halve the search space, leading to an efficient solution.
- Be cautious with potential overflow when calculating the mid-point by using low + (high - low) // 2.
Space and Time Complexity
Time Complexity: O(log n) since we binary search the range. Space Complexity: O(1) as we use a constant amount of extra space.
Solution
We use a binary search algorithm to efficiently locate the target number. We initialize two pointers: low (1) and high (n). In each iteration, we compute the mid-point, then call the guess API. Based on the response:
- If guess(mid) returns 0, we have found the number.
- If it returns -1, it indicates that our guess is higher than the pick, so we update the high pointer to mid - 1.
- If it returns 1, it indicates that our guess is lower than the pick, so we update the low pointer to mid + 1. This approach guarantees a logarithmic time solution.