Guess Number Higher or Lower

Easybinary-search
Category: Fundamentals

Approach

Guess Number Higher or Lower

Approach

Use binary search with API feedback.

Algorithm

  1. Initialize range [1, n]
  2. Binary search:
    • Guess middle number
    • If correct: return
    • If guess too high: search left half
    • If guess too low: search right half

Complexity

  • Time: O(log n) - binary search
  • Space: O(1) - constant space

Key Insights

  • Classic binary search with API calls
  • API returns: -1 (too high), 0 (correct), 1 (too low)
  • Eliminates half the search space each iteration

Solution

java
1public class Solution extends GuessGame {
2    public int guessNumber(int n) {
3        int left = 1, right = n;
4        
5        while (left <= right) {
6            int mid = left + (right - left) / 2;
7            int result = guess(mid);
8            
9            if (result == 0) {
10                return mid;
11            } else if (result < 0) {
12                right = mid - 1;
13            } else {
14                left = mid + 1;
15            }
16        }
17        
18        return -1;
19    }
20}
Loading visualizer...