Problem Statement
Given a positive integer num, determine if it is a perfect square.
Return true if num is a perfect square, otherwise return false. You cannot use built-in square root functions.
Example 1:
Input: num = 16 Output: true Explanation: 16 = 4 * 4
Example 2:
Input: num = 14 Output: false Explanation: 14 is not a perfect square
Constraints:
- 1 ≤ num ≤ 2³¹ – 1
Approach to Solve the Problem (Simple Language)
Idea:
- A perfect square is a number that can be expressed as
x * xfor some integerx. - To check if
numis a perfect square, we can use binary search instead of iterating all numbers.
Steps:
- Initialize
left = 1andright = num. - While
left <= right:- Calculate
mid = left + (right - left) / 2. - If
mid * mid == num, returntrue. - If
mid * mid < num, moveleft = mid + 1. - If
mid * mid > num, moveright = mid - 1.
- Calculate
- If no
midsatisfiesmid * mid == num, returnfalse.
Why binary search works:
- Perfect squares increase monotonically.
x*xgrows faster thanx, so binary search efficiently finds the square root.
Important Note:
- Use
longfor multiplication (mid * mid) to avoid integer overflow for largenum.
Java Code Solution (Binary Search)
public class ValidPerfectSquare {
public static boolean isPerfectSquare(int num) {
if (num < 2) return true; // 1 and 0 are perfect squares
long left = 1, right = num;
while (left <= right) {
long mid = left + (right - left) / 2;
long square = mid * mid;
if (square == num) {
return true;
} else if (square < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
public static void main(String[] args) {
int num = 16;
boolean result = isPerfectSquare(num);
System.out.println(num + " is perfect square? " + result); // Output: true
}
}
Dry Run Example
Input:
num = 16
Step-by-step Execution:
- Initialize:
left = 1,right = 16 - Iteration 1:
mid = 1 + (16-1)/2 = 8mid*mid = 64 > 16→ moveright = 7
- Iteration 2:
mid = 1 + (7-1)/2 = 4mid*mid = 16 == 16→ returntrue
Result: true → 16 is a perfect square.
Textual Diagram for Understanding
num = 16 Binary search range: [1,16] Step 1: mid=8 -> 8*8=64 -> >16 -> move right=7 Step 2: mid=4 -> 4*4=16 -> ==16 -> found perfect square Return true
Complexity Analysis
- Time Complexity: O(log num)
- Binary search halves the search space each time.
- Space Complexity: O(1)
- Only a few variables used, no extra data structures.
