InterviewPrepKit

Home / Coding / Binary Search

Guess Number Higher or Lower

easy Original β†—
Solving tips
  • Recognize binary search where the guess API is the comparator over the sorted range [1, n]; each three-way answer halves the candidates.
  • Read the API carefully: guess returns -1 when your guess is too high (secret is lower, so hi = mid-1) and 1 when the secret is higher (lo = mid+1).
  • Use mid = lo + (hi-lo)//2 to avoid overflow, since n can reach 2^31-1 and that is exactly what the bounds punish.
  • O(log n) API calls, O(1) space; step past mid (not lo = mid / hi = mid) to avoid an infinite loop on a two-value range.

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 answer from `guess` is more than a yes/no β€” it tells you which *side* of your guess the secret lies on. What does that let you discard?
Hint 2 This is exactly 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.