SDE & MLE Prep

69. Sqrt(x)

Problem

Return ⌊√x⌋ for a non-negative integer x, without any built-in power or square-root function.

Example: 4 → 2; 8 → 2

Constraints: x ≤ 2³¹ − 1.

Largest m with m*m ≤ x. Search for the first m with m*m > x, answer m − 1.

Complexity: O(log x).

class Solution:
    def mySqrt(self, x: int) -> int:
        lo, hi = 0, x + 1          # first m with m*m > x
        while lo < hi:
            m = (lo + hi) // 2
            if m * m > x:
                hi = m
            else:
                lo = m + 1
        return lo - 1