Sqrt(x) (LeetCode 69): Solution and Explanation
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. You may not call a built-in power or square root function, so the value has to be found with integer arithmetic.
Watch it run step by step
Try your own input and write the code →Intuition
The most direct approach counts upward: try 1, 2, 3 and so on, and stop at the first number whose square exceeds x. The answer is the number just before it. That takes O(√x) steps, which for x near 2³¹ means roughly 46,000 iterations. It works, but it does not use the structure of the problem.
The structure is that squaring is monotonic. If mid * mid <= x, then every smaller number also has a square at most x, and if mid * mid > x, every larger number overshoots too. So the candidates split into a yes region followed by a no region, and you want the last yes. That is exactly the shape binary search handles, applied to the range of possible answers rather than to an array.
The search range can start tighter than [0, x]. For any x of at least 2, the square root is at most x // 2, so the code searches [1, x // 2] and handles 0 and 1 up front. When the loop ends without an exact match, right has moved just below the boundary, so it points at the largest integer whose square does not exceed x, which is the floor of the square root.
This pattern, often called binary search on the answer, shows up far beyond square roots. Whenever you can test a candidate answer cheaply and the test flips from true to false exactly once as the candidate grows, you can binary search the candidate range instead of an array. Problems about eating speeds, shipping capacities and split sums all use the same skeleton.
Approach: Binary search on the answer
- If
x < 2, returnx, since the square roots of 0 and 1 are themselves. - Set
left = 1andright = x // 2. - While
left <= right, computemid = (left + right) // 2and its square. - If the square equals
x, returnmidbecause it is an exact root. - If the square is less than
x, moveleft = mid + 1; otherwise moveright = mid - 1. - When the loop ends, return
right, the largest value whose square is at mostx.
Step-by-step example
x = 8
- Since 8 is at least 2, the search range is
left = 1andright = 4. mid = 2and 2 × 2 = 4 is less than 8, soleftbecomes 3.mid = 3and 3 × 3 = 9 is greater than 8, sorightbecomes 2.- Now
left = 3is greater thanright = 2, so the loop ends and the function returns 2, the floor of √8 ≈ 2.83.
Code: Python, Java, C++
1class Solution:
2 def mySqrt(self, x: int) -> int:
3 if x < 2:
4 return x
5
6 left, right = 1, x // 2
7 while left <= right:
8 mid = (left + right) // 2
9 if mid * mid == x:
10 return mid
11 elif mid * mid < x:
12 left = mid + 1
13 else:
14 right = mid - 1
15 return right1class Solution {
2 public int mySqrt(int x) {
3 if (x < 2) return x;
4
5 long left = 1, right = x / 2;
6 while (left <= right) {
7 long mid = (left + right) / 2;
8 if (mid * mid == x) return (int) mid;
9 else if (mid * mid < x) left = mid + 1;
10 else right = mid - 1;
11 }
12 return (int) right;
13 }
14}1class Solution {
2public:
3 int mySqrt(int x) {
4 if (x < 2) return x;
5
6 long left = 1, right = x / 2;
7 while (left <= right) {
8 long mid = (left + right) / 2;
9 if (mid * mid == x) return mid;
10 else if (mid * mid < x) left = mid + 1;
11 else right = mid - 1;
12 }
13 return right;
14 }
15};Time and space complexity
O(log x)
Each iteration halves the search range, which starts at about x / 2 values, so the loop runs about log₂ x times.
O(1)
Only a few integer variables are used.
Other approaches
Newton's method (time O(log x), space O(1))
Start with a guess such as r = x and repeat r = (r + x // r) // 2 while r * r > x. Each step roughly doubles the number of correct digits, so it converges in very few iterations.
Linear scan (time O(√x), space O(1))
Increase a counter until its square passes x, then return the previous value. It is easy to verify but takes O(√x) steps.
Common mistakes
- Returning
leftinstead ofrightat the end. After the loop,leftis one past the answer. - Overflow in Java or C++ when computing
mid * midwith 32-bit integers. Use a 64-bit type or comparemidwithx / midinstead. Python integers do not overflow. - Using
right = x // 2without special-casing 1. Forx = 1, that makesright = 0and the loop never runs, which is why the code returns early forx < 2. - Converting a floating-point square root to an integer. It is disallowed here, and for very large values it can round to the wrong integer.
Frequently asked questions
Why can the upper bound be x // 2?
For any x of at least 4, (x / 2)² is at least x, so the root cannot exceed x / 2. For 2 and 3 the root is 1, which equals x // 2. Values 0 and 1 are handled separately.
What does the function return when x is not a perfect square?
It returns the floor of the square root. The binary search ends with right at the largest integer whose square is at most x, so 8 gives 2 and 15 gives 3.
Is Newton's method faster than binary search for Sqrt(x)?
Usually yes, since it converges quadratically and needs only a handful of iterations for 32-bit inputs. Binary search is easier to write correctly and is the standard interview answer.
What is the time complexity of Sqrt(x)?
Binary search takes O(log x) iterations and O(1) space. For 32-bit inputs that is at most about 31 iterations.