Problem description:

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:

1
2
Input: num = 16
Output: true

Example 2:

1
2
Input: num = 14
Output: false

Constraints:

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

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def isPerfectSquare(self, num: int) -> bool:
l, r = 0, num
while l <= r:
mid = l + (r-l) //2
if mid **2 == num:
return True
elif mid **2 > num:
r = mid-1
else:
l = mid+1

return False

time complexity: $O()$
space complexity: $O()$
reference:
related problem: