367. Valid Perfect Square LeetCode Solution

In this guide, you will get 367. Valid Perfect Square LeetCode Solution with the best time and space complexity. The solution to Valid Perfect Square problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Valid Perfect Square solution in C++
  4. Valid Perfect Square solution in Java
  5. Valid Perfect Square solution in Python
  6. Additional Resources
367. Valid Perfect Square LeetCode Solution image

Problem Statement of Valid Perfect Square

Given a positive integer num, return true if num is a perfect square or false otherwise.
A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as sqrt.

Example 1:

Input: num = 16
Output: true
Explanation: We return true because 4 * 4 = 16 and 4 is an integer.

Example 2:

Input: num = 14
Output: false
Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.

Constraints:

1 <= num <= 231 – 1

Complexity Analysis

  • Time Complexity: O(\log\texttt{num})
  • Space Complexity: O(1)

367. Valid Perfect Square LeetCode Solution in C++

class Solution {
 public:
  bool isPerfectSquare(int num) {
    long l = 1;
    long r = num;

    while (l < r) {
      const long m = (l + r) / 2;
      if (m >= num / m)
        r = m;
      else
        l = m + 1;
    }

    return l * l == num;
  }
};
/* code provided by PROGIEZ */

367. Valid Perfect Square LeetCode Solution in Java

class Solution {
  public boolean isPerfectSquare(int num) {
    long l = 1;
    long r = num;

    while (l < r) {
      final long m = (l + r) / 2;
      if (m >= num / m)
        r = m;
      else
        l = m + 1;
    }

    return l * l == num;
  }
}
// code provided by PROGIEZ

367. Valid Perfect Square LeetCode Solution in Python

class Solution:
  def isPerfectSquare(self, num: int) -> bool:
    l = bisect.bisect_left(range(num), num, key=lambda m: m * m)
    return l**2 == num
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.