Problem
Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.
An integer y is a power of three if there exists an integer x such that y == 3^x.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Constraints:
1 <= n <= 10^7
Solution
Method 1 - Maths
The task is to determine if the given integer n can be expressed as the sum of distinct powers of three. A key observation here is that powers of three are unique and non-overlapping when added (e.g., (3^0 = 1), (3^1 = 3), (3^2 = 9), etc.).
Approach
- Start by generating all possible powers of three that are less than or equal to
n. - Check if
ncan be decomposed into these powers of three by greedily subtracting the largest powers of three fromnas long asnis non-negative. - If
nbecomes zero after this process, it is possible to representnas the sum of distinct powers of three, and the result isTrue. Otherwise, returnFalse.
The approach leverages the unique representation of numbers in base 3. If a number n can be expressed as a sum of distinct powers of three, it essentially means that n, in base 3, should have only digits 0 or 1, as each power of three can be used at most once.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(log n). Each iteration reducesnsignificantly since the powers of three grow exponentially. The number of iterations is proportional to ( \log_3(n) ) or ( O(\log n) ) in terms of time complexity. - 🧺 Space complexity:
O(1). The space used is constant as no additional data structures are required to hold intermediate results.
Method 2 - Backtracking
One of the simplest way to solve it will be using backtracking.al
graph TD
A[0, 1] --> B[1, 3] & C[0,3]
B --> D[4, 9]
B --> E[1, 9]
C --> F[3, 9]
C --> G[0, 9]
D --> H[13, 27]
D --> I[4, 27]
E --> J[10, 27]
E --> K[1, 27]
F --> L[12, 27]
F --> M[3, 27]
G --> N[9, 27]
G --> O[0, 27]
H["False"]
I["False"]
J["False"]
K["False"]
L["True"]
M["False"]
N["False"]
O["False"]
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(2^k), wherekis the number of powers of three less than or equal totarget. - 🧺 Space complexity:
O(k). The space complexity arises from the recursion stack, where the depth corresponds to the total number of powers of three (k).