AAlgoLoopSpaced repetition for LeetCode
EASYBinary SearchLeetCode ↗

Guess Number Higher or Lower

The key idea

The answer space 1..n is sorted, so each guess call is a comparison that tells you which half to discard. Halving the range every call finds the pick in O(log n).

Problem

We are playing the Guess Game. I pick a number from 1 to n, and you must guess which one I picked. Every time you guess wrong, I tell you whether the number I picked is higher or lower than your guess. You call a predefined API guess(num), which returns three possible results: -1 means your guess num is higher than the number I picked, 1 means your guess num is lower than the number I picked, and 0 means your guess num is equal to the number I picked. Return the number that I picked.

Constraints

Examples

Input: n = 10, pick = 6 Output: 6
Input: n = 1, pick = 1 Output: 1
Input: n = 2, pick = 1 Output: 1

Complexity

Time: O(log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Binary Search problems