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 Higher or Lower INPUT Search Space: 1 to n 1 2 3 4 5 6 pick 7 8 9 10 guess(num) API: -1: num > pick (too high) 1: num < pick (too low) 0: num == pick (found!) n = 10 range pick = 6 hidden ALGORITHM STEPS 1 Initialize Bounds low=1, high=10 2 Calculate Mid mid = (low+high)/2 3 Call guess(mid) Check API response 4 Adjust Bounds Narrow search space Binary Search Trace: mid=5, guess(5)=1 too low mid=7, guess(7)=-1 too high mid=6, guess(6)=0 found! [1..10] --> [6..7] --> [6] O(log n) iterations FINAL RESULT Number Found! 6 Output: 6 OK - Verified! guess(6) returns 0 6 == pick (confirmed) Found in 3 guesses Key Insight: Binary Search is optimal because each guess eliminates half the remaining candidates. Time Complexity: O(log n) - For n=10, we need at most 4 guesses (log2(10) ~ 3.32). The API feedback (-1, 0, 1) tells us exactly which half to search next. TutorialsPoint - Guess Number Higher or Lower | Binary Search Approach
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