Square Root

easy

You are given a positive integer n. Return the square root of n.

If n is not a perfect square, return the floor of its square root — the greatest integer that is less than or equal to the true square root.

In other words, find the largest integer x such that x * x <= n.

Hints

You cannot use a library square-root function. What simple question can you ask each candidate integer x?
As x grows, x * x only grows. So the answers to x * x <= n look like yes, yes, yes, no, no — you want the last yes.
A sorted run of yeses followed by nos is exactly what binary search finds: probe the middle of [1, n], keep the half that can still hold the last yes, and remember the best fitting mid.

Common doubts

Two reasons. Interviews test whether you can derive it — the monotonic yes/no structure is the real lesson. And floating-point sqrt can return values like 3.9999999 for large perfect squares, so flooring it gives an off-by-one wrong answer.
Always floor. For n = 15 the true root is about 3.87, but the answer is 3 — the largest integer whose square does not exceed n — never 4.
Because when the loop ends, lo and hi have crossed and neither necessarily points at the answer. Saving ans = mid every time mid * mid <= n guarantees you return the largest value that actually fit.

Interview follow-ups

Binary search still takes only about 60 iterations. The one change: compute mid * mid in a 64-bit (or bigger) type, or rearrange the test as mid <= n / mid to avoid overflow entirely.
Yes — after the integer binary search, switch to binary search on real numbers: repeatedly halve a floating-point interval around the answer, or run Newton's method x = (x + n/x) / 2, which converges quadratically.
Any problem where feasibility is monotonic in the answer: minimum ship capacity within D days, Koko's minimum eating speed, allocating books to minimize the largest load. Binary-search the answer, test feasibility at each mid.

Fun facts

  • Newton's method for square roots — repeat x = (x + n/x) / 2 — was known to the Babylonians nearly 4,000 years ago, millennia before calculus formalized it.
  • The famous fast inverse square root hack in the Quake III engine approximated 1/sqrt(x) with a single bit-level trick and one Newton step — because calling sqrt was too slow for 1990s 3D graphics.
  • The yes-yes-no boundary you binary-search here is the same structure behind git bisect, which finds the commit that broke your build in O(log n) checkouts.

Asked at

AmazonMicrosoftGoogleAdobeSamsung
Frequently Sometimes Occasionally
Example 1
Input: n = 4
Output: 2
4 is a perfect square, so its square root is exactly 2.
Example 2
Input: n = 11
Output: 3
The square root of 11 is about 3.316. It is not a whole number, so we return the floor: 3.
Example 3
Input: n = 1
Output: 1
1 is a perfect square — its square root is 1.
Constraints

- 1 <= n <= 3*10^4

Solve this problem →