Leetcode 374. Guess Number Higher or Lower
The “Guess Number Higher or Lower” is a classic problem in computer algorithms. Here is the formal problem statement:
We are playing the Guess Game. The game is as follows:
n
.You call a pre-defined API int guess(int num)
which returns 3 possible results:
-1
: Your guess is higher than the number I picked.1
: Your guess is lower than the number I picked.0
: Your guess is equal to the number I picked.Your goal is to find the number I picked.
n
: What is the typical value range of n
? Although the general approach wouldn’t change, the value of n
might impact the efficiency details.Given common conventions and based on the problem statement, we can assume:
n
can be any value within the typical bounds of an integer.To solve this problem efficiently, a binary search algorithm is appropriate, leveraging the feedback provided by the guess(int num)
API. Here’s the plan:
low
and high
, to 1 and n
, respectively.mid = low + (high - low) / 2
.guess(mid)
API with the middle point.guess(mid)
returns 0
, we have found the number.guess(mid)
returns -1
, the target number is lower, so adjust high
.guess(mid)
returns 1
, the target number is higher, so adjust low
.This algorithm ensures a logarithmic time complexity due to the halving of the search interval in each step.
Here is the implementation in C++:
// Forward declaration of guess API.
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int low = 1, high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
int res = guess(mid);
if (res == 0) {
return mid;
} else if (res == -1) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1; // This line should never be reached if input is valid.
}
};
The time complexity of the binary search algorithm is O(log n):
log2(n)
iterations.The space complexity is O(1) as only a fixed amount of extra space (variables low
, high
, mid
, res
) is used.
This approach ensures efficiency and simplicity in finding the correct number.
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?