Sqrt(x) solution explained
Sqrt(x) asks for the integer square root of a non-negative integer x, the largest whole number m with m · m at most x, without calling a built-in square root or power function. Binary search on the answer finds it in O(log x) steps: keep the range of candidates, test the middle by squaring it, and move toward the side that can still hold the answer. Newton's method in integer form converges even faster and is a strong follow-up.
By Evin JohnPublished 7 min read
The problem, restated
You are given a whole number x that is zero or larger. Return the whole-number part of its square root: the biggest integer whose square is still no more than x. You may not use a square root function, a power operator or a floating-point shortcut, so the point is to build the search yourself.
| x | Answer | Check |
|---|---|---|
| 0 | 0 | 0 · 0 = 0 |
| 1 | 1 | 1 · 1 = 1 |
| 15 | 3 | 3 · 3 = 9, and 4 · 4 = 16 is too big |
| 16 | 4 | An exact square |
| 99 | 9 | 9 · 9 = 81, and 10 · 10 = 100 is too big |
| 2147395600 | 46340 | 46340 · 46340 is exactly this number |
What interviewers want to see
This is binary search on the answer rather than on an array. The interviewer checks that you can name the search space, write a test that splits it cleanly, choose the right midpoint rounding so the loop ends, and avoid overflow when squaring. Knowing Newton's method is a plus, especially if you can say why it converges and why the integer version stops at the right value.
Follow-ups
- Return the real square root to a given precision. Binary search on floating-point values until the range is narrower than the tolerance, or run Newton's method on reals.
- Cube root, or any k-th root. The same search, with m to the k-th power as the test; mind overflow sooner.
- Is x a perfect square? Compute the integer root and square it back.
- Why not just use floating-point sqrt and round down? For very large integers, floating-point rounding can land one off, so the result needs a correction step; integer methods avoid the question.
Brute force
Count up from 0 while the next number's square still fits. That is correct and takes O(√x) steps, which is about 46,000 for the largest 32-bit input: fine on a laptop, but it misses what the question is testing.
def int_sqrt_linear(x):
m = 0
while (m + 1) * (m + 1) <= x:
m += 1
return mThe optimal approach: binary search on the answer
The candidates 0, 1, 2 up to x line up in order, and the test m · m <= x is true for a prefix of them and false after. You want the last true. Keep lo and hi so that lo always passes the test and the answer is never above hi. Start with lo = 0, which always passes, and hi = x. Take the middle, rounded up. If it passes, the answer is at least mid, so lo = mid. If it fails, the answer is below mid, so hi = mid - 1. When lo equals hi, that is the answer.
def int_sqrt(x):
lo, hi = 0, x # lo always passes; the answer is never above hi
while lo < hi:
mid = (lo + hi + 1) // 2 # round up so lo = mid makes progress
if mid * mid <= x:
lo = mid
else:
hi = mid - 1
return loThe rounding is the detail to explain. With lo = 3 and hi = 4, a rounded-down midpoint is 3, and if 3 passes, lo = mid leaves lo at 3 forever. Rounding up gives 4, and either branch then shrinks the range. The rule of thumb: when the passing branch is lo = mid, round the midpoint up; when it is hi = mid, as in a lower-bound search, round down.
function mySqrt(x) {
let lo = 0;
let hi = x;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo + 1) / 2);
if (mid * mid <= x) lo = mid;
else hi = mid - 1;
}
return lo;
}Two overflow notes. In Java, C or C++, mid * mid overflows a 32-bit int long before mid reaches the top of the range, so compute it in a 64-bit type or compare mid with x / mid instead. In JavaScript, numbers are doubles: mid * mid is exact while the product stays at or below 2^53, and any larger product is clearly bigger than an x below 2^53 even after rounding, so the comparison stays correct. Writing the midpoint as lo plus half the gap keeps that sum exact too.
Newton's method, in integers
Newton's method improves a guess r for the root of x by averaging r with x / r. If r is too big, x / r is too small, and their average is closer. In integer form, start at r = x and repeat r = (r + x // r) // 2 while r · r is larger than x. The guesses decrease steadily and stop at exactly the integer root. Once the guess is close, the number of correct digits roughly doubles each round, so even huge inputs need only a few dozen steps.
def int_sqrt_newton(x):
r = x
while r * r > x:
r = (r + x // r) // 2
return rTrace x = 99: r goes 99, 50, 25, 14, 10, 9. At 9, 81 is at most 99, so the loop stops and 9 is the answer. Starting at x wastes a few halving steps on large inputs; starting from a power of two just above the root saves them, a refinement worth mentioning but not necessary.
Complexity
| Approach | Steps | Extra memory |
|---|---|---|
| Count up from 0 | O(√x) | O(1) |
| Binary search on the answer | O(log x) | O(1) |
| Integer Newton iteration | O(log x) to get close, then very few rounds | O(1) |
| Float sqrt plus a correction | O(1) in practice | O(1) |
Edge cases
- x = 0 and x = 1, which are their own roots.
- Perfect squares, where the answer must not drop by one.
- Numbers one below a perfect square, such as 15 or 99.
- The largest allowed input, where squaring the midpoint can overflow in fixed-width types.
Common mistakes
- Rounding the midpoint down while using lo = mid, which loops forever on two candidates.
- Squaring mid in a 32-bit type.
- Starting hi at x / 2 without handling x = 1, where x / 2 rounds to 0.
- Returning hi or mid after the loop without checking which one holds the answer.
- Using floating-point division in the Newton step, which can stall just above the root.
How to explain it out loud
Fictional example
- Candidate
- The answer is the last number whose square fits under x. The test m squared at most x is true up to some point and false after, so I can binary search over candidates instead of over an array.
- Candidate
- I keep lo as a number that passes and hi as an upper limit. Because the passing branch sets lo to mid, I round the midpoint up, otherwise two neighbors would loop forever. In Java I would square in a long.
- Candidate
- That is log x steps. If you want something faster, integer Newton's method averages r with x over r and converges in very few rounds once it is close.
Related problems
Search Insert Position is the mirror image: it finds the first value that passes a test and rounds the midpoint down. Perfect Squares uses an integer square root check inside its number theory shortcut. Writing both searches back to back is the quickest way to lock in the rounding rule.
Practicing with Natively
The rounding argument is short, which makes it easy to skip under pressure, so rehearse saying it. On Mac or Windows, Natively can read this problem from a screenshot in a practice session and suggest how to frame the search, a fair check once you have attempted it, and the transcript of your mock shows whether you mentioned overflow. See the AI interview assistant.
Questions people ask
How do you solve Sqrt(x) without a built-in function?
Binary search for the largest m with m · m at most x. Keep lo = 0 and hi = x, take the midpoint rounded up, set lo = mid if it passes and hi = mid - 1 if not, and return lo when they meet.
Why round the midpoint up in the Sqrt(x) binary search?
The passing branch sets lo = mid. With a rounded-down midpoint, two neighboring candidates can leave lo unchanged forever; rounding up guarantees the range shrinks.
What is the time complexity of Sqrt(x)?
Binary search takes O(log x) steps with O(1) memory. Counting up from 0 takes O(√x). Newton's method needs only a few rounds once its guess is close.
How does Newton's method compute an integer square root?
Start with r = x and repeat r = (r + x // r) // 2 while r · r is greater than x. The guesses decrease and stop exactly at the integer square root.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
