This problem is a classic example of Binary Search, one of the most important algorithms in programming and interviews.
๐ Problem Statement
You need to guess a number between 1 and n.
A predefined API is available:
-
guess(num) = -1โ your guess is too high -
guess(num) = 1โ your guess is too low -
guess(num) = 0โ correct guess
Return the number that was picked.
๐ Examples
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
๐ง Intuition
Instead of guessing randomly, we can eliminate half of the search space each time.
๐ This is exactly what Binary Search does.
๐ Approach (Binary Search)
Step-by-Step:
- Set:
low = 1high = n
- While
low <= high:
- Find middle:
mid = (low + high) // 2 - Call
guess(mid)
- Based on result:
- If
0โ return mid - If
-1โ search left (high = mid - 1) - If
1โ search right (low = mid + 1)
๐ป Python Code
```python id="g1"
The guess API is predefined
def guess(num): ...
def guessNumber(n):
low = 1
high = n
while low <= high:
mid = (low + high) // 2
result = guess(mid)
if result == 0:
return mid
elif result == -1:
high = mid - 1
else:
low = mid + 1
---
๐งพ Dry Run
For: n = 10, pick = 6
* low = 1, high = 10 โ mid = 5 โ guess = 1 (too low)
* low = 6, high = 10 โ mid = 8 โ guess = -1 (too high)
* low = 6, high = 7 โ mid = 6 โ guess = 0
๐ Answer = 6
---
โก Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
---
๐ฅ Why This Works
* Each step reduces search space by half
* Very efficient for large inputs
* Standard binary search pattern
---
โ ๏ธ Edge Cases
* n = 1
* pick at boundaries (1 or n)
* large values of n
---
๐ Conclusion
This problem is a direct application of Binary Search and teaches:
* Efficient searching
* Decision-based narrowing
* Logarithmic optimization
Mastering this helps solve many similar problems.
Top comments (0)