<AI/>
enru
All posts

Guess number higher or lower

LeetCode 374: Guess the picked number using a guess API and classic binary search.

Difficulty
Easy
Published
Topics
#binary search
Open on LeetCode

Problem Description

We are playing a game where you have to guess the number I picked.

The game goes as follows.

  • I pick a number from 1 to n.
  • You have to guess which number I picked.
  • Every time you guess wrong, I tell you whether the number I picked is higher or lower than your guess.

You can call a provided method guess with the signature int guess(int num) to check your guess.

The method returns:

  • -1 if your guess is higher than the number I picked;
  • 1 if your guess is lower than the number I picked;
  • 0 if your guess equals the number I picked.

Guess the number I picked.

Constraints

The picked number is always in the range from 1 to 231 - 1

Examples

Input: n = 10, picked number is 6

Answer: 6

Solution

This is a classic problem solved with binary search.

We repeat a few steps iteratively.

  1. Take the leftmost and rightmost bounds of the interval, i.e. 1 and n respectively.
  2. Find the middle of the interval and check that number:
    • if it is greater than the picked number, move the right bound to mid - 1;
    • if it is less than the picked number, move the left bound to mid + 1;
    • if it equals the picked number, we've found the answer.

We repeat this until we find the answer or the left and right bounds cross.

typescript
// For this example, the function receives the guess function as a parameter.
// In the LeetCode problem this function is provided as an API.
export const guessNumber = (n: number, guess: (num: number) => number): number => {
  let left = 1;
  let right = n;
 
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const res = guess(mid);
 
    if (res === 0) {
      return mid;
    } else if (res === 1) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
 
  return 0;
};

Complexity Analysis

Time Complexity

The complexity is O(log2 n), since we search the range of numbers with binary search.

Space Complexity

O(1), since we don't allocate additional memory.