Skip to content

Latest commit

 

History

History
71 lines (53 loc) · 2.72 KB

69.Sqrt(x)(Easy).md

File metadata and controls

71 lines (53 loc) · 2.72 KB

69. Sqrt(x) (Easy)

Date and Time: Nov 18, 2024, 16:10 (EST)

Link: https://leetcode.com/problems/sqrtx/


Question:

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Example 1:

Input: x = 4

Output: 2

Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8

Output: 2

Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.


Constraints:

  • 0 <= x <= 2^31 - 1

Walk-through:

Obeserve that the square of x is the maximum square of an integer such that m^2 <= x.

We can run Binary Search in the range [0, x] to find the value m such that m^2 <= x, then we update l = m + 1 to find the maximum m integer. Otherwise, if m^2 > x, we update r = m - 1.


Python Solution:

class Solution:
    def mySqrt(self, x: int) -> int:
        # Run binary search on x to find the max m that m^2 <= x
        # When m^2 <= x, update l = m + 1
        # When m^2 > x, update r = m - 1
        # Use res to keep track current maximum m
        
        # TC: O(log x), SC: O(1)
        res = 0
        l, r = 0, x
        while l <= r:
            m = (l + r) // 2
            if m**2 <= x:
                res = max(res, m)
                l = m + 1
            else:
                r = m - 1
        return res

Time Complexity: $O(log\ x)$, we running binary search in [0, x].
Space Complexity: $O(1)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms