File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -21,6 +21,52 @@ def perfect_square(num: int) -> bool:
21
21
return math .sqrt (num ) * math .sqrt (num ) == num
22
22
23
23
24
+ def perfect_square_binary_search (n : int ) -> bool :
25
+ """
26
+ Check if a number is perfect square using binary search.
27
+ Time complexity : O(Log(n))
28
+ Space complexity: O(1)
29
+
30
+ >>> perfect_square_binary_search(9)
31
+ True
32
+ >>> perfect_square_binary_search(16)
33
+ True
34
+ >>> perfect_square_binary_search(1)
35
+ True
36
+ >>> perfect_square_binary_search(0)
37
+ True
38
+ >>> perfect_square_binary_search(10)
39
+ False
40
+ >>> perfect_square_binary_search(-1)
41
+ False
42
+ >>> perfect_square_binary_search(1.1)
43
+ False
44
+ >>> perfect_square_binary_search("a")
45
+ Traceback (most recent call last):
46
+ ...
47
+ TypeError: '<=' not supported between instances of 'int' and 'str'
48
+ >>> perfect_square_binary_search(None)
49
+ Traceback (most recent call last):
50
+ ...
51
+ TypeError: '<=' not supported between instances of 'int' and 'NoneType'
52
+ >>> perfect_square_binary_search([])
53
+ Traceback (most recent call last):
54
+ ...
55
+ TypeError: '<=' not supported between instances of 'int' and 'list'
56
+ """
57
+ left = 0
58
+ right = n
59
+ while left <= right :
60
+ mid = (left + right ) // 2
61
+ if mid ** 2 == n :
62
+ return True
63
+ elif mid ** 2 > n :
64
+ right = mid - 1
65
+ else :
66
+ left = mid + 1
67
+ return False
68
+
69
+
24
70
if __name__ == "__main__" :
25
71
import doctest
26
72
You can’t perform that action at this time.
0 commit comments