LeetCode 367: Valid Perfect Square Solution
Master LeetCode problem 367 (Valid Perfect Square), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
367. Valid Perfect Square
Problem Explanation
Explanation
To determine if a given number is a perfect square, we can use a binary search approach. We start by setting the left boundary to 1 and the right boundary to the given number num. We then repeatedly divide the search space in half by choosing a mid value. We square the mid value and compare it with the input number num to decide whether to move the right boundary to the left half or the left boundary to the right half. We continue this process until the left boundary is less than or equal to the right boundary. If at any point we find the square of the mid value to be equal to the input number, we return true as it is a perfect square. If we exhaust the search space and do not find a perfect square, we return false.
- Time complexity: O(log(num))
- Space complexity: O(1)
Solution Code
class Solution {
public boolean isPerfectSquare(int num) {
long left = 1, right = num;
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 367 (Valid Perfect Square)?
This page provides optimized solutions for LeetCode problem 367 (Valid Perfect Square) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 367 (Valid Perfect Square)?
The time complexity for LeetCode 367 (Valid Perfect Square) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 367 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 367 in Java, C++, or Python.