InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Binary Search

Guess Number Higher or Lower

easy Original ↗ 00:00

Problem

We play a guessing game. I pick a secret number between 1 and n (inclusive). You repeatedly guess a number, and I answer through a pre-defined API:

  • guess(num) returns -1 if my secret number is lower than your guess,
  • returns 1 if my secret number is higher than your guess,
  • returns 0 if you guessed it.

Given n, return the secret number using as few calls to guess as possible.

Examples

  • Input: n = 10, secret pick = 6 → Output: 6 (Guess 5 → answer 1 (higher); guess 8 → answer -1 (lower); guess 6 → answer 0.)
  • Input: n = 1, secret pick = 1 → Output: 1 (Only one possible number; the first guess must be it.)
  • Input: n = 2, secret pick = 1 → Output: 1 (Guess 1 → answer 0 immediately.)

Constraints

  • 1 <= n <= 2^31 - 1
  • 1 <= pick <= n
  • n can be huge, so the number of guesses must be logarithmic, not linear.

Think about it first

Hint 1 Each `guess` answer tells you which side of your guess the secret lies on, not just whether you were right. What can you discard once you know that?
Hint 2 This is searching a sorted range `[1..n]` for an unknown value, where the comparison is the API call. What algorithm finds a value in a sorted range with O(log n) comparisons?
Hint 3 Maintain `lo = 1`, `hi = n`. Guess the midpoint: if the API says -1, the secret is below, so `hi = mid - 1`; if 1, `lo = mid + 1`; if 0, return `mid`. Since the pick is guaranteed to exist, the loop always terminates with an answer.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug