NeetCode #262LC-374EasyBinary SearchNC 250
← Back to All Problems#262 · #374 · Guess Number Higher or Lower(猜数字大小)
📌 Problem Statement & Constraints
This is an interactive problem. A number is picked from
1 to n. You call guess(num) which returns -1 if your guess is higher, 1 if it is lower, and 0 if correct. Return the picked number. Constraints: 1 <= n <= 2^31 - 1; at most 30 guesses.💡 Core Algorithmic Approaches
- Plain binary search over
[1, n]. guess(mid) == 0means found;-1means the guess is too high, so shrink the upper bound;1means too low, so raise the lower bound.- With
nup to 2^31, at most 31 iterations are needed, well within the 30-guess budget (the exact count isceil(log2(n+1))). - Keep the inclusive-bounds formulation, since the value space is a closed interval.
💻 Benchmark Python3 Implementation
class Solution:
def guessNumber(self, n: int) -> int:
lo, hi = 1, n
while lo <= hi:
mid = (lo + hi) // 2
r = guess(mid)
if r == 0:
return mid
if r < 0: # mid is too high
hi = mid - 1
else: # mid is too low
lo = mid + 1
return lo⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log n): about 31 iterations for the maximum n.
💾 Space Complexity
O(1): two indices.
⚠️ Interview Pitfalls & Follow-ups
- Inverting the meaning of the return value:
-1means the guess is too high, so the upper bound must decrease. Getting this backwards sends the search the wrong way. - Using a linear scan: O(n) with n up to 2^31.
- Off-by-one on the initial range: the valid range is
[1, n]inclusive, not[0, n). - Ignoring the guess budget: binary search uses
ceil(log2(n+1)) <= 31calls, which fits the limit.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
猜数字大小
猜数字游戏的规则如下:每轮游戏,我都会从 1 到 n 随机选择一个数字。请你猜选出的是哪个数字。如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能:−1 表示我选出的数字比你猜的数字小( pick < num );1 表示我选出的数字比你猜的数字大( pick > num );0 表示猜对了。返回我选出的数字。约束:1 ≤ n ≤ 2^31 − 1;1 ≤ pick ≤ n。
核心要点
- 标准二分 :在 [1, n] 上二分,根据 guess(mid) 的返回值收缩区间。
- 收缩规则 :返回 −1(pick 更小)则 r = mid − 1 ;返回 1(pick 更大)则 l = mid + 1 ;返回 0 则返回 mid。
- 本题的意义 :这是「二分查找」最纯粹的形态——数组是隐式的 [1, n] ,比较操作通过 API 完成。
- 复杂度 :O(log n)。
常见陷阱
- 把返回值含义搞反 :−1 表示「pick 比你猜的小」,因此要往 左 收缩( r = mid − 1 )。方向搞反会死循环。
- 用线性扫描 :O(n) 在 n 接近 2^31 时必然超时。
- 下界写成 0 :题目范围是 [1, n] ,下界应为 1。
- 忘记处理 g == 0 的返回 :会导致循环继续并在后续越界。
参考实现
class Solution:
def guessNumber(self, n: int) -> int:
l, r = 1, n
while l <= r:
mid = (l + r) // 2
g = guess(mid) # 题目提供的 API
if g == 0:
return mid
if g < 0: # pick < mid
r = mid - 1
else: # pick > mid
l = mid + 1
return -1