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)
1var guessNumber = function(n) {
2 let low = 1, high = n;
3 while (low <= high) {
4 let mid = Math.floor((low + high) / 2);
5 let res = guess(mid);
6 if (res === 0)
7 return mid;
8 else if (res < 0)
9 high = mid - 1;
10 else
11 low = mid + 1;
12 }
13 return -1; // should not reach here
14};
This JavaScript solution uses binary search to pinpoint the number. We utilize the guess
function to determine whether our mid-point guess was correct, high, or low, adjusting as needed.
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
This Python function applies linear search, testing each integer from 1
through n
until the correct number is found.