#483
Smallest Good Base
HardMathBinary SearchMathematical propertiesGeometric series
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log(n)) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log(n))Space O(1)
The optimal solution leverages mathematical properties of numbers. Instead of checking every base, we can derive the maximum possible base by considering the logarithmic relationship between n and k, significantly reducing the search space.
⚙️
Algorithm
5 steps- 1Step 1: Convert n to an integer.
- 2Step 2: Calculate the maximum possible value for m (the number of digits in base k) using log2(n).
- 3Step 3: For each m from max_m down to 1, calculate the potential base k using the formula k = floor(n^(1/m)).
- 4Step 4: Check if the sum of the geometric series (1 + k + k^2 + ... + k^(m-1)) equals n.
- 5Step 5: If it does, return k as the smallest good base.
solution.py12 lines
1# Full working Python code
2import math
3
4def smallestGoodBase(n: str) -> str:
5 num = int(n)
6 max_m = int(math.log(num, 2))
7 for m in range(max_m, 1, -1):
8 k = int(num ** (1 / m))
9 total = (k ** (m) - 1) // (k - 1)
10 if total == num:
11 return str(k)
12 return str(num - 1)ℹ
Complexity note: The complexity is O(log(n)) because we reduce the number of checks significantly by leveraging the properties of logarithms and geometric series.
- 1Understanding the geometric series helps in deriving the good base efficiently.
- 2Logarithmic properties allow us to limit the number of bases we need to check.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.