Floor of a Square Root Without Built-ins
Math & Bit ManipulationAuto-graded · 18 test casesLast updated
Compute the largest integer whose square does not exceed a non-negative integer, without using built-in roots or powers, using monotonic search or an iterative refinement.
Whole-Number Square Root
You are given a non-negative integer n. Return the largest non-negative integer r such that r * r <= n. In other words, return the square root of n rounded down to a whole number.
Rules
- Do not use any built-in square root function (such as
math.sqrtormath.isqrt) or the exponent operator (**,pow) to obtain the root. - The solution must work for inputs up to the maximum 32-bit signed integer value. Think about how your approach would behave in a language with fixed-width integers, where squaring a large intermediate value could overflow.
- Be ready to state the time and space complexity of your approach.
Output
Return a single integer: the floor of the square root of n.
Constraints
0 <= n <= 2^31 - 1nis an integer.- Inputs
0and1return themselves.
Examples
Example 1
Input: floor_sqrt(4)
Output: 2
Example 2
Input: floor_sqrt(8)
Output: 2
Hints
Hint 1
For a candidate value r, the condition r * r <= n is true for all small r and then false for all larger r. What does that monotonic behavior suggest about how to search?
Hint 2
Search over possible answers in a range such as [1, n // 2] for n >= 2. Decide which pointer holds the answer when the loop ends, based on the invariant that everything left of the low pointer is feasible.
Hint 3
To avoid overflow in fixed-width languages, compare mid with n // mid instead of squaring, and compute the midpoint as lo + (hi - lo) // 2. As a faster alternative, try Newton's iteration r = (r + n // r) // 2 while r * r > n.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We want the largest integer r with r * r <= n. The test r * r <= n is monotonic: it holds for every r from 0 up to some cutoff and fails for every larger r. That makes this a binary search on the answer.
- If
n < 2, returnndirectly (0 -> 0,1 -> 1). - Otherwise, the answer lies in
[1, n // 2]. It is at least 1 because1 * 1 <= n, and at mostn // 2because forn >= 2we have(n // 2)^2 >= noncen >= 4, and forn = 2, 3the answer1equalsn // 2. - At each step, take
midand comparemid * midwithn:- equal:
midis the exact root, return it; - smaller:
midis feasible, so movelo = mid + 1to look for something larger; - larger:
midis too big, so movehi = mid - 1.
- equal:
Why it is correct
Invariant: every value below lo has a square at most n, and every value above hi has a square greater than n. This holds initially (with 0 below lo, and n // 2 + 1 above hi being too large or irrelevant) and each update preserves it. The interval shrinks every iteration, and when the loop ends lo = hi + 1. Then hi is feasible and hi + 1 is not, so hi^2 <= n < (hi + 1)^2, which is exactly the floor of the square root. The early return on an exact match is only an optimization.
Overflow notes
Python integers do not overflow, but in fixed-width languages mid * mid can reach about 2^60. Use a 64-bit type, or compare mid <= n // mid, and compute the midpoint as lo + (hi - lo) // 2.
Newton's method (follow-up)
Iterate r = (r + n // r) // 2 starting from r = n while r * r > n. By AM-GM, the iterates never drop below the floor of the true root and strictly decrease while r * r > n, so the loop stops at the answer. It converges quadratically near the root, so with a good starting guess (for example 1 << ((n.bit_length() + 1) // 2)) it needs only a few iterations, at the cost of a division per step. For 32-bit inputs both methods are effectively constant time; binary search is simpler to prove correct.
Complexity
- Time:
O(log n), since the search interval halves each iteration (about 31 iterations at most). - Space:
O(1).
Reference solution
def floor_sqrt(n: int) -> int:
# 0 and 1 are their own square roots; also avoids an empty range.
if n < 2:
return n
# For n >= 2, the answer is at least 1 and at most n // 2.
lo, hi = 1, n // 2
while lo <= hi:
mid = (lo + hi) // 2
square = mid * mid
if square == n:
return mid
if square < n:
lo = mid + 1
else:
hi = mid - 1
# Loop ends with hi^2 <= n < (hi + 1)^2.
return hi