Guess Number Higher or Lower - Complete Solution Guide
Guess Number Higher or Lower is LeetCode problem 374, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n . You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num) , which returns three possible results: -1 : Your guess is higher than the number I picked (i.e. num > pick ). 1 : Your guess is lower than the number I picked (i.e. num < pick ). 0 : your guess is equal to the number I
Detailed Explanation
The 'Guess Number Higher or Lower' problem is a classic guessing game. The system picks a secret number between 1 and n (inclusive). Your task is to write code to guess this number. After each guess, you receive feedback from a pre-defined API, 'guess(num)', which returns -1 if your guess is too high, 1 if your guess is too low, and 0 if your guess is correct. The goal is to minimize the number of guesses and find the correct number efficiently.
Solution Approach
The provided code implements a binary search algorithm. It initializes a 'low' pointer to 1 and a 'high' pointer to 'n'. In each iteration, it calculates the middle value 'mid' as (low + high) / 2. It then calls the 'guess(mid)' API to get feedback. Based on the feedback, it either returns 'mid' if the guess is correct, updates 'high' to 'mid - 1' if the guess is too high, or updates 'low' to 'mid + 1' if the guess is too low. This process continues until the correct number is found.
Step-by-Step Algorithm
- Step 1: Initialize 'low' to 1 and 'high' to 'n'.
- Step 2: While 'low' is less than or equal to 'high':
- Step 3: Calculate 'mid' as the average of 'low' and 'high'. To prevent overflow use `low + (high - low) / 2`.
- Step 4: Call the 'guess(mid)' API.
- Step 5: If 'guess(mid)' returns 0, return 'mid' (the number is found).
- Step 6: If 'guess(mid)' returns -1, set 'high' to 'mid - 1' (the number is lower).
- Step 7: If 'guess(mid)' returns 1, set 'low' to 'mid + 1' (the number is higher).
- Step 8: If the loop finishes without finding the number (which shouldn't happen given the problem constraints), you can return -1 or throw an exception since the number *must* exist.
Key Insights
- Insight 1: Binary search is the most efficient approach because it halves the search space with each guess.
- Insight 2: Understanding the 'guess' API and how to use its return values to adjust the search range is crucial.
- Insight 3: Handling integer overflow when calculating the middle value 'mid' in binary search is important for large 'n'.
Complexity Analysis
Time Complexity: O(log n)
Space Complexity: O(1)
Topics
This problem involves: Binary Search, Interactive.
Companies
Asked at: Samsung.