Skip to main content

Guess Number Higher or Lower

LeetCode 374 | Difficulty: Easy​

Easy

Problem Description​

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 (the number I picked stays the same throughout the game).

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 picked (i.e. `num == pick`).

Return the number that I picked.

Example 1:

Input: n = 10, pick = 6
Output: 6

Example 2:

Input: n = 1, pick = 1
Output: 1

Example 3:

Input: n = 2, pick = 1
Output: 1

Constraints:

- `1 <= n <= 2^31 - 1`

- `1 <= pick <= n`

Topics: Binary Search, Interactive


Approach​

Binary search reduces the search space by half at each step. The key insight is identifying the monotonic property β€” what condition lets you decide to go left or right?

When to use

Sorted array, or searching for a value in a monotonic function/space.


Solutions​

Solution 1: C# (Best: 40 ms)​

MetricValue
Runtime40 ms
Memory25.5 MB
Date2021-11-25
Solution
/** 
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* int guess(int num);
*/

public class Solution : GuessGame {
public int GuessNumber(int n) {
int l=1, r = n;
int mid = -1;
while(l <= r)
{
mid = l + (r-l)/2;
int guessVal = guess(mid);
if(guessVal == 0)
{
return mid;
}
else if(guessVal == 1)
{
l = mid+1;
}
else
{
r = mid-1;
}
}

return -1;
}
}

Complexity Analysis​

ApproachTimeSpace
Binary Search$O(log n)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Precisely define what the left and right boundaries represent, and the loop invariant.