Leetcode 69: Sqrt(x)

Computing the integer square root of a number using Binary Search.

The original problem is here.

Binary Search Approach

Algorithm

Instead of an array, our search space is the range of possible integer answers from $1$ up to $x$.

My solution

class Solution:
    def mySqrt(self, x: int) -> int:
        left = 0
        right = x
        while left <= right:
            mid = (left+right)//2
            mid_sq = mid*mid
            if mid_sq == x:
                return mid
            if mid_sq > x:
                right = mid - 1
            if mid_sq < x:
                left = mid+1
        return right

Complexity Analysis