Given a positive integer num, return true if num is a perfect square or false otherwise.
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:
Input: num = 16 Output: true Explanation: We return true because 4 * 4 = 16 and 4 is an integer.
Example 2:
Input: num = 14 Output: false Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.
Constraints:
1 <= num <= 231 - 1The binary search method utilizes the principle that for a number n to be a perfect square, there exists an integer x such that x * x = n. By searching between 1 and n, binary search will narrow down the possibilities by checking the middle value, squaring it, and adjusting the search range based on whether the squared value is less than, greater than, or equal to n. This ensures a time complexity of O(log n).
The C implementation uses two pointers, left and right, to represent the range of potential roots. The mid value is checked if its square equals the input number. The range is adjusted by moving the left or right pointer, eventually finding the square or exhausting possibilities.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log n)
Space Complexity: O(1)
Newton's method is an iterative numerical approach to approximate solutions to functions. For finding a square root, the function is designed around n = x^2. By iteratively refining the guess x using x = (x + n/x) / 2, the method converges to an integer square root if one exists. This method can be faster than binary search with careful tuning.
Starts with an initial guess and iteratively applies Newton's formula to converge the guess to the correct number, utilizing standard while and arithmetic operations.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Binary Search Approach | Time Complexity: O(log n) |
| Newton's Iteration Method | Time Complexity: O(log n) |
Perfect Squares - Dynamic Programming - Leetcode 279 - Python • NeetCode • 62,696 views views
Watch 9 more video solutions →Practice Valid Perfect Square with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor