Post

Leetcode 374. Guess Number Higher or Lower

Explanation for Leetcode 374 - Guess Number Higher or Lower, and its solution in Python.

Problem

Leetcode 374 - Guess Number Higher or Lower

Example:

1
2
3
4
5
6
7
8
Input: n = 10, pick = 6
Output: 6

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

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

Approach

Another use case for binary search from number 1 to n where left = 1, and right = n

Here is the Python code for the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def guessNumber(self, n: int) -> int:
        left, right = 1, n
        while left <= right:
            mid = (left+right) // 2

            if guess(mid) == -1:
                right = mid-1
            elif guess(mid) == 1:
                left = mid+1
            else:
                return mid
        
        return -1    

Time Complexity and Space Complexity

Time Complexity: $O(log n)$

Space Complexity: $O(1)$

This post is licensed under CC BY 4.0 by the author.