69 Sqrt(x)
Implementint sqrt(int x)
.
Compute and return the square root of x.
The Idea: The naive solution would be to return the first index in the for loop through x where , since . With binary search, the idea is the same except that we begin our search within the bounds of [0, x]
, and eliminate the left or right half depending on whether the algorithm overestimated or underestimated the solution.
Below, when pow < x
, we know this resulted in a underestimation so the next iteration will extend [mid+1, high]
.
Complexity: O(log(x)) time and O(log(x)) space
Recursive Python Solution
Last updated