Valid Perfect Square
Easy
Topics
Given a positive integer n, return true if it is a perfect square (the square of some integer), and false otherwise. Do not use any built-in square-root function.
Example 1
true.Input: n = 16 Output: true
Example 2
false.Input: n = 14 Output: false
Example 3
Input: n = 1 Output: true
Constraints
- 1 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Trying every candidate up to n is O(n), and at n up to 2^31-1 that is far too slow. But mid * mid is monotonically increasing in mid, so the predicate "is mid too small" flips exactly once — which is what binary search needs.
So search the root over [1, n]. A tighter upper bound of n / 2 + 1 also works since no root above that is possible for n > 1, but it saves only a couple of iterations.
The thing that actually matters here is overflow: with n near 2^31-1, mid approaches 46341 and mid * mid exceeds a signed 32-bit int. In Java and C++ the product must be computed in 64-bit, or compared as mid <= n / mid to avoid multiplying at all. Python widens automatically, which hides the bug until the code is ported.
Approach
- Binary search
midover[1, n]. - Compare
mid * midagainstn; return true on equality, else narrow. - Return false when the range empties.
Dry Run
n = 16
lo=1 hi=16 mid=8 64 > 16 -> hi=7
lo=1 hi=7 mid=4 16 == 16 -> true
n = 14
lo=1 hi=14 mid=7 49 > 14 -> hi=6
lo=1 hi=6 mid=3 9 < 14 -> lo=4
lo=4 hi=6 mid=5 25 > 14 -> hi=4
lo=4 hi=4 mid=4 16 > 14 -> hi=3
lo > hi -> falseComplexity
- Time — O(log n): about 31 iterations at the upper bound, against O(sqrt n) for trial multiplication and O(n) for the naive scan.
- Space — O(1).
Common Pitfalls
- Overflowing
mid * midin a 32-bit type. Use 64-bit, or compare with division. - Using
sqrt(n)and testing whether the result is integral. Double precision is exact only up to 2^53, which covers this range — but rounding at the boundary still bites, so verify by squaring the candidate back. - Starting
loat 0 and never terminating onn = 0, or missing thatn = 1is a perfect square. - Writing
mid = (lo + hi) / 2wherelo + hican exceed the type. Herehistarts atnup to 2^31-1, so this one genuinely overflows —lo + (hi - lo) / 2is required, not merely preferred.
Full Solution — all languages
class Solution:
def isPerfectSquare(self, n):
lo, hi = 1, n
while lo <= hi:
mid = (lo + hi) // 2
sq = mid * mid
if sq == n:
return True
if sq < n:
lo = mid + 1
else:
hi = mid - 1
return Falseimport java.util.*;
class Solution {
public boolean isPerfectSquare(int n) {
long lo = 1, hi = n;
while (lo <= hi) {
long mid = (lo + hi) / 2;
long sq = mid * mid;
if (sq == n) return true;
if (sq < n) lo = mid + 1;
else hi = mid - 1;
}
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isPerfectSquare(int n) {
long long lo = 1, hi = n;
while (lo <= hi) {
long long mid = (lo + hi) / 2;
long long sq = mid * mid;
if (sq == n) return true;
if (sq < n) lo = mid + 1;
else hi = mid - 1;
}
return false;
}
};/**
* @param {number} n
* @return {boolean}
*/ var isPerfectSquare = function(n) {
let lo = 1, hi = n;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
const sq = mid * mid;
if (sq === n) return true;
if (sq < n) lo = mid + 1;
else hi = mid - 1;
}
return false;
};