Sqrt(x) — Solution in Python, Java & C++
Sqrt(x) solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on math and binary search.
Sqrt(x) is an easy coding problem on math and binary search.
- Difficulty: Easy
- Topics: Math, Binary Search
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a non-negative integer x, return the square root of x rounded down to the nearest integer.
Do not use any built-in exponent function or operator (sqrt, pow, **, …).
Example 1
Input: x = 4
Output: 2
Example 2
Input: x = 8
Output: 2
Explanation: √8 ≈ 2.828…, rounded down is 2.
Constraints
0 <= x <= 2147483647
Hints for Sqrt(x)
Hint 1
Binary search the answer k on the condition k*k <= x.
Hint 2
Watch for overflow in languages with fixed-size integers — compare k <= x / k instead.
How to solve Sqrt(x)
You are not searching an array — you are searching the answer space. The predicate k * k <= x is monotone: true for every k up to the root and false for every k above it. Binary searching for that boundary finds the floor of the square root without ever computing one.
Approach
- Return
xdirectly forx < 2, sincesqrt(0) = 0andsqrt(1) = 1. - Search
kin[1, x], remembering the largestkthat satisfies the predicate. - For each
mid, testmid <= x / mid— an overflow-free way of askingmid * mid <= x. - If it holds,
midis feasible: record it and search higher. Otherwise search lower. - The last recorded feasible value is the floor of the root.
Why it works
For positive integers, mid * mid <= x and mid <= x / mid (with truncating division) are exactly equivalent: if mid * mid <= x then x / mid >= mid, and if mid * mid > x then x / mid <= mid - 1. So the rewritten test decides the same predicate while never forming a product that could overflow. Monotonicity then guarantees a single crossover point, which is what the search converges on.
Complexity
- Time —
O(log x) - Space —
O(1)
Pitfalls
mid * midoverflows 32-bit integers near the upper constraint of about 2.1 billion — compare with division instead.- Handle
x = 0before the search, or the division test divides by zero. - The answer is the floor, so keep the last feasible
midrather than returning where the loop stops. - Built-in
sqrtis disallowed, and on large inputs floating point rounds wrongly at exact squares anyway.
Reference solution
Python
def mySqrt(x: int) -> int:
lo, hi = 0, x
while lo <= hi:
mid = (lo + hi) // 2
if mid * mid <= x:
lo = mid + 1
else:
hi = mid - 1
return hiJava
public static int mySqrt(int x) {
if (x < 2) return x;
int lo = 1, hi = x, best = 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (mid <= x / mid) {
best = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return best;
}C++
int mySqrt(int x) {
if (x < 2) return x;
int lo = 1, hi = x, best = 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (mid <= x / mid) {
best = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return best;
}JavaScript
var mySqrt = function(x) {
let lo = 0, hi = x;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (mid * mid <= x) lo = mid + 1;
else hi = mid - 1;
}
return hi;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 337 math problems · the whole catalogue
Learn the technique: Binary Search