We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n
. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a predefined API guess(int num)
which returns 3 possible results:
-1
: The number I picked is lower than your guess (i.e., my number is smaller).1
: The number I picked is higher than your guess (i.e., my number is larger).0
: Your guess is correct (i.e., you found my number).Implement a function int guessNumber(int n)
that uses the guess
API to find the number I picked.
n
?
1 <= n <= 2^31 - 1
.n
.To find the number that the system has picked, we can use a binary search algorithm. Since the feedback from the guess
API tells us whether the number is higher or lower, binary search is efficient and appropriate for this problem.
left = 1
and right = n
.mid = left + (right - left) // 2
.guess(mid)
function.0
, then mid
is the correct guess.-1
, the picked number is lower than mid
, so adjust the search range to left
to mid - 1
.1
, the picked number is higher than mid
, so adjust the search range to mid + 1
to right
.Here’s the implementation of the solution:
def guessNumber(n: int) -> int:
left, right = 1, n
while left <= right:
mid = left + (right - left) // 2
res = guess(mid)
if res == 0:
return mid
elif res == -1:
right = mid - 1
else:
left = mid + 1
return -1 # This line is just for completeness; the loop should always return within the loop.
## Time Complexity
The time complexity of this solution is O(log n) since we are effectively dividing the search space in half with each iteration of the binary search.
Note: Since the `guess` function is predefined, ensure it's available in the environment where you test this solution or mock it for testing purposes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?