Skip to main content
Back to problems
Leetcode
Easy
Binary Search
Simulation
Guess Number Higher Or Lower

Find a hidden number by repeatedly guessing and using higher/lower feedback.

Acceptance 0%
Problem Statement

Guess Number Higher or Lower

You are playing a guessing game with a hidden integer chosen from the range [1,n][1, n]. Each time you make a guess, you receive feedback:

  • -1 if your guess is higher than the hidden number
  • 1 if your guess is lower than the hidden number
  • 0 if your guess is exactly correct

Your task is to determine the hidden number using as few guesses as possible.

Assume you have access to an API guess(num) that returns the feedback above. Implement a function that finds the hidden number.

Input Format

  • An integer n representing the inclusive upper bound of the search range.
  • An API guess(num) that compares num with the hidden number and returns -1, 1, or 0.

Output Format

Return the hidden number.

Constraints

  • 1n1 \le n
  • The hidden number is guaranteed to be in the range [1,n][1, n].
  • You should minimize the number of calls to guess(num).
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 10, hidden number = 6

Output

6

Explanation

If you guess 5 and get 1, the hidden number is larger. If you then guess 8 and get -1, it is smaller. Continue narrowing the range until you find 6.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.