LeetCode #69 Easy

Sqrt(x)

Sqrt(x) is LeetCode 69 (Easy). Given a non-negative integer x, return its square root rounded down to a whole number.

  • Built-in power and root functions (pow, x ** 0.5, sqrt) are not allowed.
  • x goes up to 2³¹ − 1, so the square of a guess can be far larger than a 32-bit integer holds.

What you are asked for is the integer square root: the largest whole number whose square is not more than x.

Constraints
  • 0 <= x <= 2³¹ - 1
mathbinary-search
Open on LeetCode ↗
02

Intuition

Squares only grow: 0, 1, 4, 9, 16, 25 … So one guess m tells you which side the answer is on.

  • The guess fits: m * m <= x. Then m could be the answer, but a bigger number might fit too, so keep m and look right.
  • The guess is too big: m * m > x. Then m and every number above it are out, so look left.

That is binary search over the candidate answers 0 to x, not over an array: every guess halves the range. Most x are not perfect squares, so no guess lands exactly. The search keeps the last guess that fit, and that is the root rounded down.

How to spot this pattern

"Find the largest number whose value passes a test", where the test only gets harder as the number grows, is binary search on the answer. Nth roots, Koko's eating speed and ship capacity are the same search with a different test.

03

Approach

Try it first

Before reading on, pick a range that surely holds the answer, and decide what one guess tells you when its square is too big, and when it fits. Then decide which number you return when no guess squares to exactly x.

1

Set the range of candidates

Start with lo = 0, hi = x and ans = 0. The root of a non-negative whole number is never bigger than the number itself, so every possible answer lies in this range.

2

Square the middle guess

Take mid halfway between lo and hi and compute mid * mid. In C++ and Java, do the multiplication in a 64-bit type (long long, long), because the first guesses for a large x are around a billion.

3

Keep a guess that fits and look right

If the square is at most x, store ans = mid and move lo = mid + 1. mid is a valid answer so far, and only a larger number could be a better one.

4

Drop a guess that is too big and look left

Otherwise move hi = mid - 1. Every number from mid upward squares past x, so none of them can be the answer.

5

Return the last guess that fit

The loop ends when lo passes hi. By then every number up to ans has a square at most x and every number above it does not, so ans is the largest whole number whose square fits.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def mySqrt(self, x: int) -> int:
▶3 lo, hi = 0, x
▶4 ans = 0
▶5 while lo <= hi:
▶6 mid = (lo + hi) // 2
▶7 if mid * mid <= x:
▶8 ans = mid
▶9 lo = mid + 1
▶10 else:
▶11 hi = mid - 1
▶12 return ans
012345678lohiguess squared×=vs8bestcandidates 0 to 8
lo0
hi8
The root of 8 is a whole number between 0 and 8, so the bar covers every candidate. Squares grow as the number grows, which is what lets one guess throw away half the bar.
012345678guesslohiguess squared4×4=16>8best16 is over 8 → look left
mid4middle of the bar
mid²16more than 8
range0 to 3
4 squared is 16, more than 8. Every number from 4 up squares even higher, so they are all dropped and the search moves left to 0 to 3.
012345678guesslohiguess squared1×1=1≤8best11 fits → keep 1, look right
mid1middle of the bar
mid²1at most 8
range2 to 3
1 squared is 1, not more than 8, so 1 is a valid answer and becomes the best so far. A bigger number might fit too, so the search moves right to 2 to 3.
012345678guesslo higuess squared2×2=4≤8best24 fits → keep 2, look right
mid2middle of the bar
mid²4at most 8
rangejust 3
2 squared is 4, not more than 8, so 2 is a valid answer and becomes the best so far. A bigger number might fit too, so the search moves right to just 3.
012345678guessguess squared3×3=9>8best29 is over 8 → look left
mid3middle of the bar
mid²9more than 8
rangenothing left
3 squared is 9, more than 8. Every number from 3 up squares even higher, so they are all dropped, which empties the range.
012345678guess squared×=vs8best2range empty → answer 2
answer2
The range is empty. Every number up to 2 has a square of at most 8, and every number above it was too big, so 2 is the square root rounded down.
05

Common pitfalls

Squaring the guess in a 32-bit int

✗ Wrong
int mid = lo + (hi - lo) / 2;
if (mid * mid <= x)
✓ Right
int mid = lo + (hi - lo) / 2;
if ((long long)mid * mid <= x)

For x = 2147395599 the first guess is mid = 1073697799, whose square is about 1.15 × 10¹⁸. An int cannot hold that, so the product wraps to a meaningless value that can look smaller than x, and the search heads the wrong way. Python integers never overflow, so only C++ and Java hit this.

Returning lo after the loop

✗ Wrong
return lo
✓ Right
return ans  # or hi

When the loop stops, lo sits one past the last guess that fit. For x = 8 it ends with lo = 3 and hi = 2, and 3 × 3 = 9 is already too big. The saved ans (equal to hi here) is the correct 2.

06

Edge cases

x = 0

The range is just 0 to 0. The only guess, 0, fits, so the answer is 0 with no special case.

x = 2147483647, the largest input

The answer is 46340: its square, 2,147,395,600, fits, while 46341² = 2,147,488,281 is too big. The search needs about 31 rounds.

07

Complexity

Time
O(log x)
Space
O(1)
The range starts with x + 1 candidates and halves every round, so a 32-bit x needs at most about 32 rounds. Only three numbers are stored.
08

Sqrt(x) FAQ

Is Newton's method faster than binary search here?

Usually, yes. Start with r = x and repeat r = (r + x // r) // 2 while r * r > x; with whole-number division it stops exactly on the rounded-down root. It needs far fewer rounds for big x, but it is harder to argue correct in an interview, so binary search is the common answer.

Why not call sqrt() and round down?

The problem bans it. Outside the problem, a double root is exact enough for every 32-bit x, but for 64-bit inputs it can be off by one near perfect squares, which is why whole-number methods matter.

How is Valid Perfect Square different?

Valid Perfect Square (LeetCode 367) runs the same search but answers yes or no: it returns true only if some guess squares to exactly num, instead of keeping the last guess that fit.