Sponsored
Sponsored
This approach uses binary search to guess the number. We maintain two pointers, low
and high
, representing the current range of numbers we need to search. Then, we guess the middle number of the range and adjust our range based on the response from the guess
API. If the guessed number is correct, we return it. Otherwise, we adjust the low
or high
pointers and repeat the process until the number is guessed correctly.
Time Complexity: O(log n)
Space Complexity: O(1)
1def guessNumber(n):
2 low, high = 1, n
3 while low <= high:
4 mid = (low + high) // 2
5 res = guess(mid)
6 if res == 0:
7 return mid
8 elif res < 0:
9 high = mid - 1
10 else:
11 low = mid + 1
12 return -1 # should not reach here
This Python function uses binary search to find the target number. It calls the guess
API to check if the guessed number is correct or needs adjustment.
This approach is a straightforward linear search that iterates from 1
to n
guessing each number one by one until it finds the correct pick. It's simple but not efficient for larger values of n
and is provided here primarily for educational purposes.
Time Complexity: O(n)
Space Complexity: O(1)
1
In Java, this approach iterates over each number starting from 1
until the correct number is guessed, which is the easiest and most intuitive approach.