Code Logo

Guess Number Higher or Lower

Published at24 Jul 2026
Easy 0 views
Like0

We are playing the Guess Game. The game is as follows: I pick a number between 1 and n. You have to guess which number I picked. Each time you guess, I call the API guess(num) which returns one of three possible results: -1 (your guess is too high), 1 (your guess is too low), or 0 (you guessed correctly). Return the number I picked.

This is a classic interactive binary search problem. Instead of comparing against an array, we compare against the feedback from the API. Initialize lo = 1 and hi = n. Guess the midpoint. If the API returns 0, we found the number. If it returns -1 (too high), search the left half. If it returns 1 (too low), search the right half.

Each API call halves the search space. For n up to 2³¹ - 1, only about 31 calls are needed — far fewer than a linear scan. The binary search pattern here is the standard closed-interval version (lo <= hi) because we check equality explicitly with the API's 0 response.

Edge cases include n = 1 (only one possible number), the picked number being 1 or n (boundary values), and ensuring the mid calculation does not overflow.

The guess API provides ternary feedback: too high (-1), too low (1), or correct (0). Unlike standard binary search that compares values, this interactive approach relies on API responses. The ternary feedback allows exact match detection within the loop without post-loop correction.

Example Input & Output

Example 1
Input
100, pick=1
Output
1
Explanation

Picked number is the minimum.

Example 2
Input
10, pick=6
Output
6
Explanation

Guessing the picked number 6.

Example 3
Input
100, pick=100
Output
100
Explanation

Picked number is the maximum.

Example 4
Input
5, pick=3
Output
3
Explanation

Picked number in the middle.

Example 5
Input
1, pick=1
Output
1
Explanation

Only one possible number.

Algorithm Flow

Recommendation Algorithm Flow for Guess Number Higher or Lower
Recommendation Algorithm Flow for Guess Number Higher or Lower

Solution Approach

Binary search between 1 and n. Use guess(mid) feedback to narrow the range. Return when guess returns 0.

function solution(n) {
  var lo = 1, hi = n;
  while (lo <= hi) {
    var mid = Math.floor((lo + hi) / 2);
    var g = guess(mid);
    if (g === 0) return mid;
    if (g === -1) hi = mid - 1;
    else lo = mid + 1;
  }
  return -1;
}

Time O(log n), Space O(1).

Best Answers

java
class Solution {
    static int pick = 6;
    static int guess(int v) {
        if (v == pick) return 0;
        if (v > pick) return -1;
        return 1;
    }
    public int solution(int n) {
        int lo = 1, hi = n;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int g = guess(mid);
            if (g == 0) return mid;
            if (g == -1) hi = mid - 1;
            else lo = mid + 1;
        }
        return -1;
    }
}