The problem, in one line. Given a non-negative integer, return its square root rounded down to a whole number, without a built-in square root. LeetCode 69.
The tell. No list is given, but the answer sits in a known range from 0 to x, and “does this number squared still fit?” is yes for small guesses and no for big ones. A yes-then-no line is searchable.
The wrong first idea
Try 0, 1, 2, 3 and so on until the square passes x, then return the last one that fit.
r = 0
while (r + 1) * (r + 1) <= x:
r += 1
return r
Correct. It takes about the square root of x steps, which is small for 100 but about three billion for a number near 10 to the 19th. Halving the range of guesses needs about sixty.
The invariant
Hold a range of guesses. lo is a guess known to fit, and hi is the highest guess still possible. Try the guess in between, and keep it when it fits.
flowchart LR A["x = 8<br/>lo 0, hi 8<br/>mid 4, 16 > 8<br/>hi = 3"] --> B["lo 0, hi 3<br/>mid 2, 4 <= 8<br/>lo = 2"] B --> C["lo 2, hi 3<br/>mid 3, 9 > 8<br/>hi = 2"] C --> D["lo = hi = 2<br/>answer 2"]
The sentence that stays true every step: lo squared still fits in x, and nothing above hi does. The answer is the biggest guess that fits, so when lo and hi meet, that is it.
The solution
def my_sqrt(x):
lo, hi = 0, x
while lo < hi:
mid = (lo + hi + 1) // 2 # round up, so lo = mid always makes progress
if mid * mid <= x:
lo = mid # mid fits, the answer is mid or bigger
else:
hi = mid - 1 # mid is too big
return lo
print(my_sqrt(4))
print(my_sqrt(8))
print(my_sqrt(0))
2
2
0
func mySqrt(x int) int {
lo, hi := 0, x
for lo < hi {
mid := (lo + hi + 1) / 2 // round up, so lo = mid always makes progress
if mid*mid <= x {
lo = mid // mid fits, the answer is mid or bigger
} else {
hi = mid - 1 // mid is too big
}
}
return lo
}
Same three calls print 2, 2, 0.
Complexity
- Time O(log x): the range of guesses halves every loop.
- Space O(1): two guesses and the middle.
Traps
- Rounding the middle down while writing
lo = mid. Onx = 1the range is 0 to 1, the middle is 0, andlonever moves, so the loop never ends. - Returning
hior rounding up. The root of 8 is about 2.83, and the question wants 2, so the answer is the biggest guess that fits, never the smallest that overshoots. - Squaring a guess in a fixed-size integer type. A guess near 50,000 squared passes 2 billion and wraps negative in 32 bits. Compare
mid <= x // midthere instead.
Next in the ladder
Koko Eating Bananas swaps “does this square fit?” for “is this eating speed fast enough?”. The search is identical, but now the yes or no test is a small loop over the input.