Problem Description
Given a positive integer num, determine if num is a perfect square—i.e., whether there exists an integer whose square equals num—without using any built-in library function like sqrt.
Key Insights
- Recognize that if num is a perfect square, it will have an exact integer square root.
- Use binary search between 1 and num/2 (when num >= 4) to efficiently determine if there is an integer mid such that mid * mid == num.
- The binary search stops when the search space is exhausted, meaning num is not a perfect square if no integer mid found.
Space and Time Complexity
Time Complexity: O(log(num)) Space Complexity: O(1)
Solution
We solve the problem using binary search. By checking mid * mid at each step, we narrow down the interval where the square root could lie, eventually determining if an exact integer square root exists. The trick is setting the correct search boundaries: numbers less than 4 can be handled directly, and for larger numbers, the square root can never be more than num/2. This avoids using built-in functions and deals gracefully with large inputs.