Sqrt(x)
Easy
Topics
Given a non-negative integer n, return the integer square root of n (the floor of the true square root). Do not use built-in sqrt.
Example 1
2²
3²
the largest square not exceeding 4
√4 is truncated to an integer, not rounded: the answer is the largest whole number whose square is still at most 4. 2² = 4 fits and 3² = 9 does not, so the answer is 2.
The two squares either side of the answer.
Input: n = 4 Output: 2
Example 2
2²
3²
the largest square not exceeding 8
Input: n = 8 Output: 2 Explanation: floor(2.828...) = 2.
Constraints
- 0 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The integer square root is the largest m with m² ≤ n. Since m² grows monotonically, binary-search for that boundary instead of scanning.
Approach
- Binary-search
min[0, n]. - If
m² ≤ n, recordmand search higher. - Otherwise search lower.
- Return the last valid
m.
Walkthrough
n = 8
lo=0 hi=8 mid=4 16>8 -> hi=3
lo=0 hi=3 mid=1 1<=8 ans=1 lo=2
lo=2 hi=3 mid=2 4<=8 ans=2 lo=3
lo=3 hi=3 mid=3 9>8 hi=2 -> answer 2Complexity
- Time — O(log n): binary search halves the range each step.
- Space — O(1): a few integers.
Common Pitfalls
mid * midcan overflow 32-bit ints for large n — use 64-bit or comparemidagainstn / mid.- The midpoint itself is the other overflow to watch: prefer
lo + (hi - lo) / 2over(lo + hi) / 2, which can wrap negative in Java and C++ oncelo + hiexceeds2^31 - 1.
Full Solution — all languages
class Solution:
def mySqrt(self, n):
if n < 2:
return n
lo, hi = 1, n // 2
while lo <= hi:
mid = (lo + hi) // 2
if mid * mid <= n:
lo = mid + 1
else:
hi = mid - 1
return hiimport java.util.*;
class Solution {
public int mySqrt(int n) {
if (n < 2) return n;
long lo = 1, hi = n / 2;
while (lo <= hi) {
long mid = (lo + hi) / 2;
if (mid * mid <= n) lo = mid + 1;
else hi = mid - 1;
}
return (int) hi;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int mySqrt(int n) {
if (n < 2) return n;
long lo = 1, hi = n / 2;
while (lo <= hi) {
long mid = (lo + hi) / 2;
if (mid * mid <= (long)n) lo = mid + 1;
else hi = mid - 1;
}
return (int) hi;
}
};/**
* @param {number} n
* @return {number}
*/ var mySqrt = function(n) {
if (n < 2) return n;
let lo = 1, hi = Math.floor(n / 2);
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (mid * mid <= n) lo = mid + 1;
else hi = mid - 1;
}
return hi;
};