Valid Perfect Square solution explained
To check whether a positive integer is a perfect square without calling a square-root function, binary search for an integer root between 1 and the number: square the middle value, compare it with the number, and halve the range. That takes O(log n) steps and O(1) space. Newton's method with integer division converges even faster and is the usual follow-up.
By Evin JohnPublished 7 min read
The problem in plain words
You are handed one positive integer. Decide whether it is the square of some integer. The catch is a rule: no library square-root function, and usually no exponent tricks either, because the point is to see you build the search yourself. In the common version the input fits in a 32-bit signed integer, which matters for overflow in some languages.
| Input | Answer | Why |
|---|---|---|
| 144 | true | 12 × 12 = 144 |
| 145 | false | 12² is 144 and 13² is 169, nothing in between |
| 1 | true | 1 × 1 = 1, the smallest valid input |
| 1000000 | true | 1000 × 1000 |
| 999999 | false | Just below a square is never a square |
What this question checks
It is a small problem with three places to slip: the loop bounds, the overflow of mid × mid in languages with fixed-size integers, and the exit condition. Interviewers often use it as a warm-up before a harder search question, and they listen for whether you frame it as searching over possible answers. Mentioning Newton's method unprompted is a bonus, not a requirement.
Slow approach: count upward
Start at 1 and keep increasing a candidate root while its square is below the number. When the loop stops, either the square equals the number or it has just passed it. The work is about √n iterations, so roughly 46,000 steps for the largest 32-bit input. That is not terrible, but it ignores the ordering that makes a much faster search possible.
def is_square_slow(num):
root = 1
while root * root < num:
root += 1
return root * root == numMain approach: binary search on the root
Squares grow with their roots, so the function f(x) = x × x is increasing for positive x. That means you can search for the root the same way you search a sorted list. Keep a range [lo, hi] that would contain the root if one exists, starting with 1 and the number itself. Square the middle. If it matches, you are done. If it is too small, the root must be larger, so move lo above mid. If it is too large, move hi below mid. When the range empties, no integer root exists.
def is_square(num):
lo, hi = 1, num
while lo <= hi:
mid = (lo + hi) // 2
sq = mid * mid
if sq == num:
return True
if sq < num:
lo = mid + 1
else:
hi = mid - 1
return Falsefunction isSquare(num) {
let lo = 1;
let hi = num;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
const sq = mid * mid;
if (sq === num) return true;
if (sq < num) lo = mid + 1;
else hi = mid - 1;
}
return false;
}The overflow question
In Java or C++ with 32-bit ints, mid × mid overflows as soon as mid passes 46,340, and the comparison silently goes wrong. Use a 64-bit type for the square, or compare mid with num / mid using integer division. In JavaScript, numbers are doubles that hold integers exactly up to 2^53. A square larger than that loses precision, but it is then far larger than any 32-bit input, so the comparison still says too big. Near the actual root the squares are small and exact. That reasoning is worth one sentence if the interviewer asks.
Follow-up: Newton's method with integers
Newton's method refines a guess x for the root of num by replacing it with the average of x and num / x. Using integer division throughout and starting from x = num, the guesses fall steadily until x × x is no longer above num. At that point x is the integer part of the square root, and the number is a perfect square exactly when x × x equals it. Convergence is quadratic once the guess is close, so even huge inputs settle in a handful of steps.
def is_square_newton(num):
x = num
while x * x > num:
x = (x + num // x) // 2
return x * x == numA third idea, sometimes raised as trivia, uses the fact that the sum of the first k odd numbers is k². Subtract 1, 3, 5 and so on until you reach zero or go negative. It is still O(√n), so it is a curiosity rather than an improvement.
Complexity
| Approach | Time | Extra space | Comment |
|---|---|---|---|
| Count upward | O(√n) | O(1) | Easy to state, slow for large n |
| Subtract odd numbers | O(√n) | O(1) | A neat fact, same speed |
| Binary search | O(log n) | O(1) | The standard answer |
| Integer Newton | About O(log n), much faster once close | O(1) | Good follow-up |
Edge cases to test
- 1, which is a square and makes lo and hi start equal.
- 2 and 3, the smallest non-squares.
- The largest square that fits in 32 bits, 46,340², and the numbers on either side of it.
- The largest 32-bit input, 2,147,483,647, which is not a square.
- Values one below a square, such as 99, where a sloppy exit test can report true.
Common mistakes
- Calling a square-root function or raising to the power 0.5, which the problem rules out.
- Letting mid × mid overflow in a 32-bit language.
- Starting the search at 0, then dividing by mid in the num / mid comparison.
- Using while lo < hi with hi = mid - 1, which can skip the root when the range shrinks to one value.
- Returning after the loop based on lo × lo without checking for equality.
How to explain it out loud
Fictional example
- Candidate
- Squaring is increasing for positive numbers, so instead of computing a root I can search for one. The root, if it exists, is between 1 and num.
- Candidate
- I square the midpoint and narrow the range by half each time. On 145, I would pass through guesses whose squares are too big or too small and end with an empty range, so I return false.
- Interviewer
- Anything to watch in Java?
- Candidate
- The square overflows an int above 46,340, so I would store it in a long or compare mid with num divided by mid.
Related problems in this set
H-Index II uses the same search on a sorted list instead of on numbers. Guess Number Higher or Lower is the purest version of the idea, where an oracle replaces the squaring step. Arranging Coins searches for a row count with a triangular number in place of a square. The algorithm interview questions page has more on binary search patterns.
Drilling it with Natively
For quick warm-up problems like this, Natively can read a screenshot of the statement and outline an approach, which is useful as a check after you have coded your own. It also keeps a transcript of a mock interview on your computer, so you can see whether you raised the overflow point without being asked. Learn more about an AI interview assistant for Mac and Windows.
Questions people ask
How do you check for a perfect square without sqrt?
Binary search for an integer root between 1 and the number. Square the midpoint, compare it with the number, and keep the half that could still contain the root. It takes O(log n) steps.
What is the overflow problem in Valid Perfect Square?
In languages with 32-bit integers, mid × mid overflows once mid passes 46,340. Store the square in a 64-bit type or compare mid with num / mid using integer division.
Is Newton's method faster than binary search here?
Usually, yes. Integer Newton iteration starts at the number and repeatedly averages x with num // x; it converges quickly once close and stops when x × x is no longer above the number.
What is the simplest correct solution?
Count a candidate root upward from 1 until its square reaches or passes the number. It is correct but takes about the square root of n steps.
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.
