Valid Perfect Square using Python

Validating perfect squares is a popular coding interview question. Here you will be given an integer, and you have to check if the integer is a perfect square. So, if you want to learn how to validate perfect squares, this article is for you. In this article, I will take you through how to solve the problem of Valid Perfect Square using Python.

Valid Perfect Square using Python

When we square an integer, the output is a perfect square. In the problem of validating a perfect square, you will be given an integer n. To solve this problem, you need to check whether the given integer n is a square of an integer.

For example, look at the input and output of this problem shown below:

  • Input: 16 | Output: True (4×4 = 16)
  • Input: 14 | Output: False

If the input integer is the square of a number, your output will be True. Otherwise, False.

Valid Perfect Square using Python

I hope you have understood what the problem of validating the perfect square means. Now, below is how to solve this problem using the Python programming language:

def isPerfectSquare(num):
    left = 1
    right = num

    while left < right:
        mid = (left + right) // 2
        if mid * mid == num:
            return True
        
        elif mid * mid < num:
            left = mid + 1
        
        elif mid * mid > num:
            right = mid
    return False

print(isPerfectSquare(49))
Output: True

So this is how to validate perfect squares using Python. You can find many more practice questions for coding interviews solved and explained using Python here.

Summary

When we square an integer, the output is a perfect square. In the problem of validating a perfect square, you will be given an integer n. To solve this problem, you need to check whether the given integer n is a square of an integer. I hope you liked this article on validating perfect squares using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1500

Leave a Reply