Back to writing

Valid Perfect Square


Given a positive integer num, write a function which returns True if num is a perfect square else False.

Follow up: Do not use any built-in library function such as sqrt.

 

Example 1:

Input: num = 16
Output: true

Example 2:

Input: num = 14
Output: false

 

Constraints:

  • 1 <= num <= 2^31 - 1

 class Solution:
    def isPerfectSquare(self, num: int) -> bool:

        if num < 2:
            return num

        left = 0
        right = num//2

        while left <=right:
            mid = left + (right-left)//2
            x =mid*mid

            if  x == num:
                return True
            elif x > num:
                right = mid -1
            else:
                left = mid + 1

        return False

From python 3.7 dict guarantees that order will be kept as they inserted, and popitem will use LIFO order but we need FIFO type system. so we need OrderedDict which have popIten(last = T/F) for this req. One thing, next(iter(dict)) will return the first key of the dict

Python