LeetCode 374: Guess Number Higher or Lower Solution
Master LeetCode problem 374 (Guess Number Higher or Lower), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
374. Guess Number Higher or Lower
Problem Explanation
Explanation
To solve this problem, we can use a binary search algorithm. The idea is to iteratively guess the number in the middle of the range (1 to n) and adjust the search range based on the response from the guess function. If the guess is too high, we update the upper bound of the range. If the guess is too low, we update the lower bound of the range. We continue this process until we find the correct number.
-
Algorithm:
- Initialize
lowas 1 andhighas n. - While
lowis less than or equal tohigh, do the following:- Calculate the mid point as
(low + high) / 2. - Make a guess using
guess(mid). - Update the search range based on the guess:
- If the guess result is -1, set
high = mid - 1. - If the guess result is 1, set
low = mid + 1. - If the guess result is 0, return
mid.
- If the guess result is -1, set
- Calculate the mid point as
- Initialize
-
Time Complexity: O(log n) - Binary search reduces the search space by half in every iteration.
-
Space Complexity: O(1) - Constant extra space is used.
Solution Code
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;
int result = guess(mid);
if (result == 0) {
return mid;
} else if (result == -1) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1; // Not found
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 374 (Guess Number Higher or Lower)?
This page provides optimized solutions for LeetCode problem 374 (Guess Number Higher or Lower) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 374 (Guess Number Higher or Lower)?
The time complexity for LeetCode 374 (Guess Number Higher or Lower) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 374 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 374 in Java, C++, or Python.