Sqrt(x)
Pattern: Binary search on the answer
The integer square root is the largest r with r × r ≤ x. The guesses 0 to x pass and then fail, so binary search for the last one that passes, rounding mid up.
The problem
Given a whole number x ≥ 0, return its square root rounded down, without any built-in power or square root function.
For example, x = 4 gives 2, and x = 8 gives 2, because the true root 2.828… rounds down to 2.
The function name mySqrt matches LeetCode. Use the link above for the exact statement and limits.
Think first
- Which numbers
rsatisfyr × r ≤ x? What shape do they form? - Is the answer the first or the last guess that passes?
- How big can
r × rget, and does it fit in 32 bits?
Hints
Brute force, and why it fails
Try r = 0, 1, 2, … until r × r passes x: O(√x), which is about 46,000 steps for the largest int. Binary search
takes about 31 steps.
The key insight
You do not need an array to binary search. Any range of guesses with a pass/fail check that changes once can be halved the same way.
Dry run
x = 8. The answer r is the last guess with r × r at most 8. Guesses run from 0 to 8.
The plan
lo = 0, hi = x
while lo < hi:
mid = lo + (hi - lo + 1) / 2
if mid * mid <= x: lo = mid
else: hi = mid - 1
return lo
Complexity
- Time
O(log x)- Space
O(1)
The range of guesses halves each step.
Edge cases
x = 0andx = 1: the answer isx.- Perfect squares, such as 16: the answer is exact.
x = 2,147,483,647:mid × midneeds 64 bits. The answer is 46,340.
I've built my logic, show the code
Java
class Solution {
public int mySqrt(int x) {
long lo = 0, hi = x; // the answer is the last r with r * r <= x
while (lo < hi) {
long mid = lo + (hi - lo + 1) / 2; // round up, so lo = mid always moves forward
if (mid * mid <= x) lo = mid; // mid is small enough: the answer is mid or bigger
else hi = mid - 1;
}
return (int) lo;
}
}C++
class Solution {
public:
int mySqrt(int x) {
long long lo = 0, hi = x; // the answer is the last r with r * r <= x
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2; // round up, so lo = mid always moves forward
if (mid * mid <= x) lo = mid; // mid is small enough: the answer is mid or bigger
else hi = mid - 1;
}
return static_cast<int>(lo);
}
};Python
class Solution:
def mySqrt(self, x: int) -> int:
lo, hi = 0, x # the answer is the last r with r * r <= x
while lo < hi:
mid = (lo + hi + 1) // 2 # round up, so lo = mid always moves forward
if mid * mid <= x:
lo = mid # mid is small enough: the answer is mid or bigger
else:
hi = mid - 1
return loCommon mistakes
- Rounding
middown withlo = mid, which loops forever on two guesses. - Computing
mid * midin 32 bits. - Returning the first guess that fails instead of the last one that passes.