Valid Perfect Square (LeetCode 367): Solution and Explanation

Easy
Math
Binary Search

We must decide whether num is the square of some integer without calling sqrt. Squares increase with the side length, so binary search over sides 1..num finds the exact root if there is one in O(log num) steps.

Intuition

If num is a perfect square, its root is a whole number somewhere between 1 and num.

The square of a side grows as the side grows. Testing one side tells us whether every smaller side or every larger side can be ruled out.

That one-directional answer is exactly what binary search needs: each probe throws away half of the remaining sides.

Approach: Binary search on the side length

  1. Set lo = 1 and hi = num.
  2. While lo <= hi, take mid in the middle and compute sq = mid * mid with 64-bit arithmetic.
  3. If sq equals num, return true.
  4. If sq is smaller than num, set lo = mid + 1; otherwise set hi = mid - 1.
  5. When the window is empty, return false.

Step-by-step example

num = 14
  1. lo = 1, hi = 14, mid = 7. 49 > 14, so hi = 6.
  2. mid = 3. 9 < 14, so lo = 4.
  3. mid = 5. 25 > 14, so hi = 4.
  4. mid = 4. 16 > 14, so hi = 3.
  5. lo = 4 > hi = 3. 3² = 9 is too small and 4² = 16 is too big, so return false.

Code: Python, Java, C++

1class Solution:
2    def isPerfectSquare(self, num: int) -> bool:
3        lo, hi = 1, num
4        while lo <= hi:
5            mid = (lo + hi) // 2
6            sq = mid * mid
7            if sq == num:
8                return True
9            if sq < num:
10                lo = mid + 1
11            else:
12                hi = mid - 1
13        return False
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log num)

The window of candidate sides halves on every probe, starting from num candidates.

Space

O(1)

Only lo, hi, mid and the square are kept.

Other approaches

Newton's method (time O(log num), space O(1))

Iterate x = (x + num / x) / 2 from x = num until x * x <= num, then check x * x == num. Converges very quickly.

Sum of odd numbers (time O(sqrt(num)), space O(1))

Perfect squares are sums 1 + 3 + 5 + .... Subtract consecutive odd numbers from num and check whether you land on exactly 0.

Common mistakes

  • Computing mid * mid in a 32-bit int. For num near 2^31 the first mid is about 10^9 and its square overflows; use long, long long or int64.
  • Writing mid = (lo + hi) / 2 with 32-bit ints, which can overflow when lo and hi are both large. lo + (hi - lo) / 2 is safe.
  • Starting lo at 0 and forgetting num = 1, or using a strict loop condition lo < hi that never tests the last candidate.

Frequently asked questions

Can I set hi to num / 2 to save a step?

Yes for num >= 4, because the root is at most num / 2 then. You must still handle num = 1, whose root is 1 and larger than num / 2.

Why not just use floating-point division mid > num / mid?

Integer division num / mid avoids overflow, but you then need care with the remainder to detect equality. Using a 64-bit square is simpler and exact.

How is this related to Sqrt(x)?

Sqrt(x) uses the same search but returns the floor of the root. Here we only check whether the search lands exactly on the root.