#326
Power of Three
EasyMathRecursionMathematical propertiesLogarithmic calculations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(log n) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of dividing repeatedly, we can use logarithms to check if n is a power of three. If log base 3 of n is an integer, then n is a power of three.
⚙️
Algorithm
3 steps- 1Step 1: If n is less than or equal to 0, return false.
- 2Step 2: Calculate log base 3 of n using the change of base formula: log(n) / log(3).
- 3Step 3: Check if the result is an integer by comparing it to its rounded value.
solution.py8 lines
1# Full working Python code
2import math
3
4def isPowerOfThree(n):
5 if n <= 0:
6 return False
7 log_result = math.log(n, 3)
8 return log_result.is_integer()ℹ
Complexity note: The time complexity is O(1) because we are performing a constant number of operations regardless of the size of n. The space complexity is also O(1) since we are using a constant amount of space.
- 1Understanding logarithms can simplify problems involving powers.
- 2Checking for powers of numbers can often be done using mathematical properties.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.