NeetCode #264LC-367EasyBinary Search
← Back to All Problems#264 · #367 · Valid Perfect Square(有效的完全平方数)
📌 Problem Statement & Constraints
Given a positive integer
num, return true if it is a perfect square, i.e. it equals k * k for some integer k. You must not use any built-in square-root function. Constraints: 1 <= num <= 2^31 - 1.💡 Core Algorithmic Approaches
- Binary search for the integer square root over
[1, num](or[1, num // 2]for a tighter range whennum > 1). - If any midpoint squares exactly to
num, return true. - Alternatively, use the property that perfect squares are sums of consecutive odd numbers
1 + 3 + 5 + ..., which gives an O(sqrt(n)) loop. - The binary search is O(log n) and is the expected answer.
💻 Benchmark Python3 Implementation
class Solution:
def isPerfectSquare(self, num: int) -> bool:
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 False
# Odd-number accumulation: perfect squares are sums of the first k odd numbers
class Solution2:
def isPerfectSquare(self, num: int) -> bool:
i = 1
while num > 0:
num -= i
i += 2
return num == 0⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log n) for binary search; O(sqrt(n)) for the odd-number accumulation.
💾 Space Complexity
O(1): a few scalars.
⚠️ Interview Pitfalls & Follow-ups
- Using
math.sqrt(num).is_integer(): the problem forbids built-in square-root functions, and floating-point rounding can misjudge values near the 2^31 boundary. - Using
num0.5**: same precision concern and also a built-in operator. - Setting
hi = num // 2: safe only fornum > 1; fornum = 1the range would be empty. Usinghi = numis simplest and still O(log n). - Overflowing
mid * midin fixed-width languages: fornumnear 2^31 this is fine in 64-bit, but Python is unconditionally safe.