Practice Guess Number Higher or Lower
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Problem Statement
A fixed secret number is chosen from 1 through n. Find and return it using the provided API int guess(int num). The API returns -1 when num is greater than the secret, 1 when num is less than the secret, and 0 when they are equal.
Source: Guess Number Higher or Lower on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
n = 10, pick = 6
6
With inclusive bounds [1,10], binary search first tries 5. The API returns 1, meaning the secret is larger, so the bounds become [6,10]. Trying 8 returns -1 and narrows them to [6,7]. Trying 6 returns 0, so return 6. The example reveals pick only to explain the test; the solution must learn it through guess calls. Be careful with the signs: -1 means the guess is too large, not that the secret should be searched for in the upper half.
# Example 2
n = 1, pick = 1
1
The initial interval [1,1] contains only the number 1. Guessing 1 returns 0, so the answer is 1. There is no smaller positive candidate to test. This case checks that a binary-search loop still handles an interval containing a single value rather than stopping before that candidate is examined.
# Example 3
n = 2, pick = 1
1
For inclusive bounds [1,2], the lower midpoint is 1. The API returns 0 immediately because the secret is 1, so the answer is 1. No second call is needed. The search range starts at 1, not 0; keeping that boundary avoids querying a number outside the stated range.
Constraints
Related LeetCode Problems
Practice more problems similar to Guess Number Higher or Lower.
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.