Leetcode 367. Valid Perfect Square
Determine if a given positive integer num
is a perfect square. A perfect square is an integer that is the square of some integer. In other words, a perfect square is the product of some integer with itself.
For example, 1, 4, 9, and 16 are perfect squares while 3 and 10 are not.
bool isPerfectSquare(int num);
num = 16
true
num = 14
false
num
?
1 <= num <= 2^31 - 1
.sqrt()
?
sqrt()
function. Instead, we should demonstrate an algorithmic approach.2^31 - 1
, a solution should be efficient for large inputs within this range.The problem can be solved using several methods, but we’ll demonstrate a couple of efficient approaches:
Binary search can determine if num
is a perfect square efficiently by checking the middle of the range from 1
to num
.
left
to 1 and right
to num
.left
is less than or equal to right
:
mid
as the midpoint between left
and right
.mid * mid
equals num
, return true.mid * mid
is less than num
, move left
to mid + 1
.mid * mid
is more than num
, move right
to mid - 1
.Newton’s Method (or Newton-Raphson method) can also be employed to iteratively approach the square root of num
.
x
equal to num
.guess
using the formula:
guess = (guess + num / guess) / 2
guess * guess
is close enough to num
.Here is the implementation using the Binary Search approach:
bool isPerfectSquare(int num) {
if (num < 1) return false; // Edge case handling
long left = 1, right = num; // Use long to prevent potential overflow
while (left <= right) {
long mid = left + (right - left) / 2;
long square = mid * mid;
if (square == num) {
return true;
} else if (square < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
This solution ensures that num
is efficiently checked for being a perfect square using binary search. Given its logarithmic time complexity, it works well even for larger values within the range of a 32-bit signed integer.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?