KatInterview

Floor of a Square Root Without Built-ins

Math & Bit ManipulationAuto-graded · 18 test cases
MediumAuto-gradedMath & Bit Manipulationbinary-searchmathnewton-method

Last 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.sqrt or math.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 - 1
  • n is an integer.
  • Inputs 0 and 1 return 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.