1519. Guess From the Shortlist
A quiz host has secretly picked a number, and you are told it is one of the values in candidates, which is given in strictly increasing order. You can ask the host about a value g through the global function guess(g): it returns 0 if the secret is exactly g, -1 if the secret is lower than g, and 1 if the secret is higher than g.
Return the secret number, using at most 11 calls to guess. Only guess values that appear in candidates: binary search over the candidate indices, discarding the half that the answer rules out.
The hidden number is supplied by the judge and is not passed as an argument; guess is a global function, not a method of game. Aim for O(log n) calls and time, with O(1) extra space.
Example 1
- Input:
- candidates = [2,9,14,37], game = 14
- Output:
- 14
- Explanation:
The secret 14 is the third candidate, so a couple of guesses on candidate values locate it.
Example 2
- Input:
- candidates = [-5,0,5], game = -5
- Output:
- -5
- Explanation:
The secret is the smallest candidate, so the search keeps moving left.
Constraints
1 ≤ candidates.length ≤ 1000
-109 ≤ candidates[i] ≤ 109
candidates is strictly increasing
the hidden number is in candidates
at most 11 calls to guess
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
- Calls
- You may call
guess(num)at most 11 times per case. It is provided; you do not write it.
Expected complexity
- Time
- O(log n)
- Space
- O(1)