Check if a number is perfect square using binary search. Time complexity : O(Log(n)) Space complexity: O(1) >>> perfect_square_binary_search(9) True >>> perfect_square_binary_search(16) True >>> perfect_square_binary_search(1) True >>> perfect_square_binary_
(n: int)
| 22 | |
| 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 | |
| 70 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected