#374

Guess Number Higher or Lower

Easy
Binary SearchInteractiveBinary SearchInteractive Problems
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal solution uses a binary search approach, which significantly reduces the number of guesses needed. By halving the search space with each guess, we can quickly hone in on the correct number.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers, left = 1 and right = n.
  2. 2Step 2: While left is less than or equal to right, calculate mid = (left + right) // 2.
  3. 3Step 3: Call the guess API with mid. If the result is 0, return mid. If it's -1, set right = mid - 1. If it's 1, set left = mid + 1.
solution.py10 lines
1def guessNumber(n):
2    left, right = 1, n
3    while left <= right:
4        mid = (left + right) // 2
5        if guess(mid) == 0:
6            return mid
7        elif guess(mid) == -1:
8            right = mid - 1
9        else:
10            left = mid + 1

Complexity note: The time complexity is O(log n) because we halve the search space with each guess. The space complexity is O(1) as we are using a constant amount of space.

  • 1Binary search drastically reduces the number of guesses needed.
  • 2Understanding how to adjust search boundaries is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.