Coding · Easy · Free
Integer square root (floor of √x)
CodingBinary SearchFresher
Approach
- Binary search on answer in range
[0, x]. - If
mid * mid <= x, record mid and search higher. - Use long for multiplication to avoid overflow.
Java Solution
Java
public class SqrtInteger {
public static int mySqrt(int x) {
if (x < 2) return x;
int lo = 1, hi = x / 2, ans = 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
long sq = (long) mid * mid;
if (sq <= x) {
ans = mid;
lo = mid + 1;
} else hi = mid - 1;
}
return ans;
}
}| Complexity | |
|---|---|
| Time | O(log x) |
| Space | O(1) |
Interview tip: Classic "search on answer" pattern used in capacity and allocation problems.