Date and Time: Nov 18, 2024, 16:10 (EST)
Link: https://leetcode.com/problems/sqrtx/
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++ orx ** 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.
0 <= x <= 2^31 - 1
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
.
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: [0, x]
.
Space Complexity: