Sqrt(x) (LeetCode 69): Solution and Explanation

Easy
Math
Binary Search

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. If x < 2, return x, since the square roots of 0 and 1 are themselves.
  2. Set left = 1 and right = x // 2.
  3. While left <= right, compute mid = (left + right) // 2 and its square.
  4. If the square equals x, return mid because it is an exact root.
  5. If the square is less than x, move left = mid + 1; otherwise move right = mid - 1.
  6. When the loop ends, return right, the largest value whose square is at most x.

Step-by-step example

x = 8
  1. Since 8 is at least 2, the search range is left = 1 and right = 4.
  2. mid = 2 and 2 × 2 = 4 is less than 8, so left becomes 3.
  3. mid = 3 and 3 × 3 = 9 is greater than 8, so right becomes 2.
  4. Now left = 3 is greater than right = 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 right

Time and space complexity

Time

O(log x)

Each iteration halves the search range, which starts at about x / 2 values, so the loop runs about log₂ x times.

Space

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 left instead of right at the end. After the loop, left is one past the answer.
  • Overflow in Java or C++ when computing mid * mid with 32-bit integers. Use a 64-bit type or compare mid with x / mid instead. Python integers do not overflow.
  • Using right = x // 2 without special-casing 1. For x = 1, that makes right = 0 and the loop never runs, which is why the code returns early for x < 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.