Leetcode 69. Sqrt(x)
Explanation for Leetcode 69 - Sqrt(x), and its solution in Python.
Problem
Example:
1
2
3
4
5
6
7
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 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.
Approach
We can use binary search from 1 to x
- if mid * mid == x, return mid
- if mid * mid < x, update left pointer
- if mid * mid > x, update right pointer
Here is the Python code for the solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def mySqrt(self, x: int) -> int:
left, right = 1, x
res = 0
while left <= right:
mid = (left+right) // 2
if mid * mid < x:
left = mid + 1
# we want to update res in case sqrt(x) needs to be rounded off
res = mid
elif mid * mid > x:
right = mid - 1
else:
return mid
return res
Time Complexity and Space Complexity
Time Complexity: $O(log n)$
Space Complexity: $O(1)$
This post is licensed under CC BY 4.0 by the author.