Valid Perfect Square

Easy

Topics
MathBinary Search

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

4²16
5²25
16 is exactly 4², so the answer is true.
The two squares either side of n.
Input:  n = 16
Output: true

Example 2

3²9
4²16
14 falls strictly between 3² = 9 and 4² = 16, so no whole number squares to it and the answer is false.
Input:  n = 14
Output: false

Example 3

1²1
2²4
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

  1. Binary search mid over [1, n].
  2. Compare mid * mid against n; return true on equality, else narrow.
  3. 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 -> false

Complexity

  • 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 * mid in 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 lo at 0 and never terminating on n = 0, or missing that n = 1 is a perfect square.
  • Writing mid = (lo + hi) / 2 where lo + hi can exceed the type. Here hi starts at n up to 2^31-1, so this one genuinely overflows — lo + (hi - lo) / 2 is 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 False
Asked at LinkedIn
SensAI
Beta
Tap the mic to stop voice mode