Skip to content
LC-0069 Easy LeetCode

69. Sqrt(x)

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 40% Topics: Math, Binary Search
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(logn)
# Space: O(1)

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 2:
            return x

        left, right = 1, x // 2
        while left <= right:
            mid = left + (right - left) // 2
            if mid > x / mid:
                right = mid - 1
            else:
                left = mid + 1

        return left - 1


Solution from kamyu104/LeetCode-Solutions · MIT