Sqrt(x)
Difficulty: Easy · Pattern: Binary Search · LeetCode #69
Return the square root of a non-negative integer x, rounded down, without using built-in power or sqrt functions.
Examples
text
4 → 2
8 → 2 (√8 ≈ 2.83)
0 → 0Hints
- Find the largest integer m with m² ≤ x.
- Binary search m in [0, x].
Approach
Binary search for the last m with m·m ≤ x (use upper-middle mid = (lo + hi + 1) // 2 with lo = mid to avoid infinite loops). O(log x). Newton's method also converges very fast.
Complexity
Time: O(log x). Space: O(1).
Python solution
def mySqrt(x):
lo, hi = 0, x
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * mid <= x:
lo = mid
else:
hi = mid - 1
return loJavaScript solution
function mySqrt(x) {
let lo = 0, hi = x;
while (lo < hi) { const mid = Math.floor((lo + hi + 1) / 2); if (mid * mid <= x) lo = mid; else hi = mid - 1; }
return lo;
}