NeetCode #265LC-69EasyBinary SearchNC 250
← Back to All Problems#265 · #69 · Sqrt(x)(x 的平方根)
📌 Problem Statement & Constraints
Given a non-negative integer
x, return the square root of x rounded down to the nearest integer. You must not use any built-in exponent function or operator. Constraints: 0 <= x <= 2^31 - 1.💡 Core Algorithmic Approaches
- Binary search for the largest integer
kwithk * k <= x. - Use the upper-bias midpoint
(lo + hi + 1) // 2together withlo = mid/hi = mid - 1, which finds the last valid value. - The range is
[0, x], sincexitself bounds the answer. - Newton's method converges faster in practice but binary search is the clearest answer.
💻 Benchmark Python3 Implementation
class Solution:
def mySqrt(self, x: int) -> int:
lo, hi = 0, x
while lo < hi:
mid = (lo + hi + 1) // 2 # upper-biased to avoid an infinite loop
if mid * mid <= x:
lo = mid # mid is valid -> keep searching right
else:
hi = mid - 1
return lo
# Newton's method: quadratic convergence
class Solution2:
def mySqrt(self, x: int) -> int:
if x < 2:
return x
r = x
while r * r > x:
r = (r + x // r) // 2 # integer Newton step
return r⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log x) for binary search; O(log log x) iterations for Newton's method.
💾 Space Complexity
O(1): a few scalars.
⚠️ Interview Pitfalls & Follow-ups
- Using the lower-biased midpoint
(lo + hi) // 2withlo = mid: this loops forever whenhi == lo + 1. The upper bias is required. - Using
math.sqrt: explicitly forbidden by the problem. - Returning the float result: the answer is an integer (floor of the square root).
- Overflowing in fixed-width languages:
mid * midcan exceed 32 bits for largex; Python is safe.