Guess Number Higher or Lower - Problem
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked (the number I picked stays the same throughout the game).
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
-1: Your guess is higher than the number I picked (i.e.num > pick)1: Your guess is lower than the number I picked (i.e.num < pick)0: Your guess is equal to the number I picked (i.e.num == pick)
Return the number that I picked.
Input & Output
Example 1 — Basic Case
$
Input:
n = 10, pick = 6
›
Output:
6
💡 Note:
Using binary search: guess 5 (too low), then 8 (too high), then 6 (correct). Found in 3 guesses.
Example 2 — Edge Case
$
Input:
n = 1, pick = 1
›
Output:
1
💡 Note:
Only one number possible, so first guess is correct.
Example 3 — Large Range
$
Input:
n = 2, pick = 1
›
Output:
1
💡 Note:
Binary search starts with middle (1.5 → 1), which happens to be correct.
Constraints
- 1 ≤ n ≤ 231 - 1
- 1 ≤ pick ≤ n
Visualization
Tap to expand
Understanding the Visualization
1
Input
Range [1, n] and unknown picked number
2
Binary Search
Guess middle, adjust range based on API response
3
Output
Return the picked number
Key Takeaway
🎯 Key Insight: Binary search eliminates half the possibilities with each guess, making it logarithmically efficient
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code