An interactive visualization of how binary search finds the integer square root. Watch the algorithm narrow down the search space and compare squares step by step.
Binary Search LeetCode 69 ↗ Easyx, return the square root of x,
rounded down to the nearest integer (i.e., the floor value).pow(x, 0.5) or x ** 0.5).
fun mySqrt(x: Int): Int { if (x < 2) return x var lo = 1; var hi = x / 2 while (lo <= hi) { val mid = (lo + hi) / 2 val sq = mid.toLong() * mid if (sq == x.toLong()) return mid else if (sq < x) lo = mid + 1 else hi = mid - 1 } return hi // floor of sqrt}
We need to find the largest integer mid such that mid * mid ≤ x.
Since the function f(mid) = mid * mid is monotonically increasing,
binary search is a natural fit: if mid² ≤ x, the answer is at least mid,
so we search higher; if mid² > x, mid is too large, so we search lower.
x < 2, return x directly (sqrt(0) = 0, sqrt(1) = 1)lo = 1, hi = x // 2 (for x ≥ 2, sqrt(x) ≤ x/2)mid = (lo + hi) // 2 and sq = mid * midmidmid might be the answer but could be larger → lo = mid + 1mid is too large → hi = mid - 1hi holds the floor of the square root
Each binary search iteration halves the search space. We start with at most x / 2 candidates,
so we need at most O(log x) iterations. Each iteration does O(1) work (one multiplication and comparison).