Valid Perfect Square
Introduction
Given a positive integer num
true
num
false
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 sqrt
Example 1
Output: true
Explanation: We return true because 4 * 4 = 16 and 4 is an integer.
Example 2
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 Math.sqrt(num)
num
true
false
O(√n)
We can solve this problem using binary search, which runs in O(log n)
left =1
right = num
while
mid =
square
mid
-
If
value is equal tosquare
, then returnnum
since the square computed usingtrue
is a perfect integer.mid
-
If
value is greater than num, this means that the target lies on left side, so we will updatesquare
value toright
.mid-1
-
If
value is less than num, this means that the target lies on right side, so we will updatesquare
value toleft
.mid+1
If that num
false
public class ValidPerfectSquare {
static boolean isPerfectSquare(int num) {
int left = 1;
int right = num;
while(left <= right) {
int mid = left + (right - left) /2;
long sqrt = (long)mid * mid;
if (sqrt == num) {
return true;
} else if (sqrt > num) {
right = mid-1;
} else {
left = mid+1;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(isPerfectSquare(16));
System.out.println(isPerfectSquare(14));
System.out.println(isPerfectSquare(2147483647));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(log n) time where n
num
Space complexity: O(1).
Above implementations source code can be found at