Leetcode: Square Root (Sqrt)
1 min readDec 28, 2016
Sqrt(x) | LeetCode OJ
Implement int sqrt(int x). Compute and return the square root of x.
leetcode.com
Square root of n will lie in the range [1, n]. So we need to search for x in a sorted array such that x*x equals given number. As you can see its a simple application of binary search
Refer to the blog post on binary search to understand how the algorithm and the code works
Time and space complexity are O(log n) and O(1) respectively
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
low, high = 0, x + 1
mid = (low + high) / 2
while mid != low:
val = mid * mid
if val == x:
return mid
if val < x:
low = mid
else:
high = mid
mid = (low + high) / 2
return low