Guess Number Higher or Lower - Problem
Welcome to the classic Guess the Number game! ๐ฏ
In this interactive puzzle, a secret number has been chosen from the range 1 to n. Your mission is to find this hidden number using the minimum number of guesses possible.
How it works:
- You make a guess by calling the API function
guess(num) - The API returns helpful feedback:
-1: Your guess is too high (the secret number is lower)1: Your guess is too low (the secret number is higher)0: Bingo! You found the secret number
Goal: Return the secret number that was chosen.
Challenge: Can you solve it efficiently without trying every possible number?
Input & Output
example_1.py โ Basic Case
$
Input:
n = 10, pick = 6
โบ
Output:
6
๐ก Note:
We need to find the number 6 in the range 1-10. Using binary search: guess(5)โ1 (too low), guess(8)โ-1 (too high), guess(6)โ0 (found!). Return 6.
example_2.py โ Edge Case Low
$
Input:
n = 1, pick = 1
โบ
Output:
1
๐ก Note:
Only one possible number. First guess(1) returns 0, so we immediately return 1.
example_3.py โ Edge Case High
$
Input:
n = 2, pick = 2
โบ
Output:
2
๐ก Note:
Two possible numbers. Using binary search: guess(1)โ1 (too low), guess(2)โ0 (found!). Return 2.
Visualization
Tap to expand
Understanding the Visualization
1
Start in the Middle
Always guess the middle number of your current range
2
Eliminate Half
Based on 'too high' or 'too low', eliminate half the remaining possibilities
3
Repeat
Continue halving the search space until you find the answer
4
Guaranteed Success
You'll find any number in at most โlogโ(n)โ guesses
Key Takeaway
๐ฏ Key Insight: Binary search transforms a potentially massive search into a logarithmic problem, making it feasible to search even billions of numbers in just ~30 guesses!
Time & Space Complexity
Time Complexity
O(log n)
Each guess eliminates half of the remaining search space, so we need at most logโ(n) guesses
โก Linearithmic
Space Complexity
O(1)
We only need a few variables to track the left and right boundaries
โ Linear Space
Constraints
- 1 โค n โค 231 - 1
- 1 โค pick โค n
- Important: The guess API is provided and you cannot modify it
- You should minimize the number of calls to the guess API
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code