SDE & MLE Prep

374. Guess Number Higher or Lower

Problem

A number was picked from 1…n. The provided API guess(num) returns −1 if the pick is lower than num, 1 if it is higher, and 0 if it's correct. Return the picked number.

Example: n = 10, pick = 6 → 6

Constraints: n ≤ 2³¹ − 1.

Classic binary search where the comparison is the provided guess(num) API: -1 means the pick is lower than num, 1 higher, 0 found.

Complexity: O(log n) calls.

class Solution:
    def guessNumber(self, n: int) -> int:
        lo, hi = 1, n
        while True:
            mid = (lo + hi) // 2
            g = guess(mid)          # provided by LeetCode
            if g == 0:
                return mid
            if g < 0:
                hi = mid - 1
            else:
                lo = mid + 1