#1780

Check if Number is a Sum of Powers of Three

Medium
MathMathematical PropertiesBase Conversion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal solution leverages the properties of numbers in base 3. If the number can be represented as a sum of distinct powers of three, its ternary representation should not contain the digit '2'. This is because '2' indicates that we would need to use the same power of three more than once.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert the number n to its base 3 representation.
  2. 2Step 2: Check if any digit in the base 3 representation is '2'.
  3. 3Step 3: Return true if no '2' is found, otherwise return false.
solution.py6 lines
1def checkPowersOfThree(n):
2    while n > 0:
3        if n % 3 == 2:
4            return False
5        n //= 3
6    return True

Complexity note: The time complexity is O(log n) because we are effectively dividing the number by 3 in each iteration, which reduces the number of digits we need to check. The space complexity is O(1) as we are using a constant amount of space.

  • 1The ternary representation of a number provides insight into whether it can be expressed as a sum of distinct powers of three.
  • 2If any digit in the base 3 representation is '2', it cannot be formed by distinct powers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.