Sqrt(x)
EasyTop Interview 150 Math & GeometryGrammarlyZohoProblem
Given a non-negative integer x, return its square root rounded down to the nearest whole number.
You may not use a built-in power or square-root function or operator.
Constraints
- 0 ≤ x ≤ 2³¹ − 1
Examples: pick one to animate
Solutions
TimeO(log x)
SpaceO(1)
Time: Each probe throws away half of the candidate roots between 0 and x.
Space: Only lo, hi, mid and ans are stored.
Squares grow with the number, so "does mid * mid fit under x?" is true for small
numbers and false for big ones. Binary search the border: when it fits, remember mid and look higher;
when it does not, look lower. Use a 64-bit type so mid * mid cannot overflow.