Valid Perfect Square — LeetCode 367 Python Solution
EasyMathBinary Search
- Problem
- #367
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- num = 16
- Output
- true
- Explanation
- We return true because 4 * 4 = 16 and 4 is an integer.
Python solution
Python
class Solution:
def isPerfectSquare(self, num: int) -> bool:
l = bisect_left(range(1, num + 1), num, key=lambda x: x * x) + 1
return l * l == numComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n), where n is the given number |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 367. Valid Perfect Square is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 367. Valid Perfect Square?
- LeetCode 367. Valid Perfect Square is rated Easy on LeetCode.
- What is the time complexity of LeetCode 367. Valid Perfect Square?
- The Python solution on this page runs in O(\log n), where n is the given number.
- What is the space complexity of LeetCode 367. Valid Perfect Square?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 367. Valid Perfect Square cover?
- LeetCode 367. Valid Perfect Square is tagged Math and Binary Search on LeetCode.