Given a positive integer
A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as
Output: true
Explanation: We return true because 4 * 4 = 16 and 4 is an integer.
Output: false
Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.
Constraints:
1 <= nums.length <= 231-1
Contents
Solution 1 - Using binary search
In the problem statement, it is mentioned that we cannot use any inbuilt functions such as
We can solve this problem using binary search, which runs in
-
If
square value is equal tonum , then returntrue since the square computed usingmid is a perfect integer. -
If
square value is greater than num, this means that the target lies on left side, so we will updateright value tomid-1 . -
If
square value is less than num, this means that the target lies on right side, so we will updateleft value tomid+1 .
If that
Complexity Analysis:
Time complexity: Above code runs in O(log n) time where
Space complexity: O(1).
Above implementations source code can be found at