Skip to main content
Back to problems
#374
Easy Algorithms

Guess number higher or lower

Binary Search Interactive
57.2% acceptance
Jan 12, 2026
4220
688
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.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  unsafe fn guess_number(n: i32) -> i32 {
    let mut left = 1;
    let mut right = n;
    
    while left <= right {
      let mid = left + (right - left) / 2;
      match unsafe { guess(mid) } {
        0 => return mid,
        -1 => right = mid - 1,
        _ => left = mid + 1,
      }
    }
    
    left
  }
}