A number pick has been chosen from 1 to n, and you must find it. You cannot see it; you can only call a provided function guess(num), which returns −1 if pick is lower than num, 1 if pick is higher, and 0 if num is the pick.
Return the chosen number.
Example 1
Input: n = 16, pick = 13 Output: 13 Why: guesses 8 (higher), 12 (higher), 14 (lower), 13 (correct)
2 more examples and the constraints
Example 2
Input: n = 5, pick = 5 Output: 5 Why: the pick can be n itself
Example 3
Input: n = 3, pick = 1 Output: 1 Why: the pick can be 1 as well
Constraints
- 1 ≤ n ≤ 2³¹ − 1 (2,147,483,647)
- 1 ≤ pick ≤ n
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Ternary searchO(log n)
- Binary searchO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Worst-case guesses for n = 2³¹ − 1 | Verdict |
|---|---|---|---|
| Ternary search | O(log n) | Passes; about 40 guesses | |
| Binary search | O(log n) | Best; at most 31 guesses |
n = the top of the range. Counting up from 1 would be O(n): up to 2 billion guesses.
Edge cases to test
- n = 1. The only possible pick is 1, and the first guess finds it.
- Pick at either end. pick = 1 or pick = n must still be reached; the range shrinks onto the end.
- Largest n. With n = 2,147,483,647 and a high pick, (lo + hi) / 2 overflows a 32-bit int.
- Reply sign. −1 means the pick is lower than the guess, not that the guess is lower.
Common mistakes
- Computing mid as (lo + hi) / 2, which overflows in Java and C++ for large n.
- Reading −1 as "guess higher" and moving the wrong bound.
- Setting lo = mid or hi = mid instead of mid ± 1, which can loop forever.
How to talk through it
- 1Clarify. What exactly do −1 and 1 mean? Is the pick always in range? How big can n be?
- 2Give the brute force. Guess 1, 2, 3 and so on: O(n), up to 2 billion calls.
- 3Name the search. Every reply says which side the pick is on, so halve the range each time: binary search.
- 4Code it safely. mid = lo + (hi − lo) / 2, and move lo or hi past mid by one.
- 5Test out loud. Run n = 1, pick = 1, pick = n and n = 2³¹ − 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?