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
Guess Number Game: Find Pick=6 in Range [1,10]Input Range:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Pick = 6 (unknown to us)Binary Search Process:Guess 5: +1Guess 8: -1Guess 6: 0Too low, go rightToo high, go leftFound!Only 3 guesses needed instead of 6 (linear search)Output: 6
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
Asked in
Google 25 Facebook 18 Microsoft 15 Amazon 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen