↓Skip to main content
  1. LeetCode/

LeetCode 374: Guess Number Higher or Lower

·1 min· ·
LeetCode Easy Binary-Search Interactive
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted ×4

Approach
#

Standard binary search (Binary Search Template 1) with the comparison replaced by guess: -1 means my number is too high, go left; 1 means too low, go right; 0 is correct.

My Solution
#

class Solution:
    def guessNumber(self, n: int) -> int:
        l, r = 1, n
        while True:
            mid = (l + r) // 2
            g = guess(mid)
            if g == 0:
                return mid
            if g < 0:
                r = mid - 1
            else:
                l = mid + 1

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • guess reports my guess relative to the answer; -1 means too high.

Interview Explanation
#

I binary search 1 to n, going left or right by guess’s result and returning when it is 0. Time O(log n).

Related

LeetCode 278: First Bad Version
·1 min
LeetCode Easy Binary-Search Interactive
LeetCode 278 note: find the first version where isBadVersion is True with a lower-bound binary search, calling the API O(log n) times
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer