Leetcode 374. Guess Number Higher or Lower
You’re playing a guessing game with your friend. The game is as follows:
n
.Your goal is to determine the target number with the fewest guesses.
You are given a function int guess(int num)
that returns:
-1
if num
is higher than the target number1
if num
is lower than the target number0
if num
is the target numberYour task is to implement the function int guessNumber(int n)
that returns the target number.
n
is always greater than or equal to 1?n
be a very large number, necessitating concerns about performance?n
is minimal (e.g., 1)?To efficiently determine the target number, we can use a binary search algorithm. By continually halving the search range based on feedback from the guess()
function, we can pinpoint the target number in logarithmic time.
Steps:
low
and high
, to 1 and n
respectively.low
is less than or equal to high
:
mid
.guess(mid)
function to get feedback.guess(mid)
function returns 0, we have found the target number and can return it.public class Solution extends GuessGame {
public int guessNumber(int n) {
int low = 1;
int high = n;
while (low <= high) {
int mid = low + (high - low) / 2; // Avoid potential overflow
int result = guess(mid);
if (result == 0) {
return mid;
} else if (result == -1) {
high = mid - 1;
} else {
low = mid + 1;
}
}
// If no number is found (though per problem statements, this point shouldn't be reached)
return -1;
}
}
The time complexity of the above solution is O(log n)
, thanks to the binary search approach. Each iteration halves the search space, leading to a logarithmic number of iterations relative to the size of n
.
n
using minimal comparisons.guess()
function for feedback.O(log n)
time, which is efficient for even large values of n
.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?