Leetcode: Square root of x
The task is to implement a square root method without using math.sqrt
or **
or pow
or any similar function. Any digits after the decimal point do not to be returned. This is effectively the floor(sqrt(n))
function.
The first idea is to simply try out every number and multiply it with itself until the square root is found. If the next number is greater than n
, return the previous number. This is however not very efficient as it has a time complexity of O(sqrt(n))
in every case.
To speed this process up, we can use binary search. The idea is to always double the size of the steps until we reach the target number or overshoot. If we overshoot, take half of the number and start at 1
again, then double, and so on.
The solution then looks as follows.
Runtime: 84 ms, faster than 28.09% of Python3 online submissions for Sqrt(x).
Memory Usage: 13.8 MB, less than 56.92% of Python3 online submissions for Sqrt(x).