The βValid Perfect Squareβ problem asks whether a given positive integer num
is a perfect square. In other words, we need to determine if there exists an integer x
such that x * x == num
.
Example:
num = 16
β Output: true
(since 4 * 4 = 16)num = 14
β Output: false
This problem helps you practice binary search in a mathematical context, reinforcing how to apply divide-and-conquer techniques outside of traditional array-based problems. It also encourages thinking about precision, overflow, and integer arithmetic.
Since the square root of num
must lie between 1 and num
(inclusive), we can use binary search to check if there exists an integer whose square equals num
. Instead of checking every integer sequentially, we divide the range in half with each step.
left = 1
and right = num
.left <= right
:
mid = Math.floor((left + right) / 2)
.mid * mid
.mid * mid == num
, return true
.mid * mid < num
, the square is too small β move left = mid + 1
.mid * mid > num
, the square is too large β move right = mid - 1
.false
.
Input: num = 25
Time Complexity: O(log n), because we divide the range of possible answers by 2 in each step.
Space Complexity: O(1), using only constant extra memory.
num = 1
β should return truenum = 0
β problem typically restricts to positive integers, but should handle gracefullyThe βValid Perfect Squareβ problem is a great demonstration of how binary search can be applied to numerical properties rather than sorted data structures. This technique is both time-efficient and elegant, making it ideal for problems where brute-force iteration is too slow.