Smallest Good Base - Problem
Given an integer n represented as a string, return the smallest good base of n.
We call k >= 2 a good base of n, if all digits of n base k are 1's.
In other words, n represented in base k should be 111...1 (all ones).
Input & Output
Example 1 — Basic Case
$
Input:
n = "13"
›
Output:
"3"
💡 Note:
13 in base 3 is 111: 1×3² + 1×3¹ + 1×3⁰ = 9 + 3 + 1 = 13. Base 2 gives 1101 (not all 1s), so 3 is the smallest good base.
Example 2 — Small Number
$
Input:
n = "4"
›
Output:
"3"
💡 Note:
4 in base 3 is 11: 1×3¹ + 1×3⁰ = 3 + 1 = 4. Base 2 gives 100 (not all 1s), so 3 is the smallest good base.
Example 3 — Edge Case
$
Input:
n = "2"
›
Output:
"2" would be invalid, but smallest good base is actually base n-1 = "1" which is invalid. By definition, we return n-1 when no valid base ≥ 2 exists, but 2 in base 1 would be "11" conceptually.
Constraints
- n is represented as a string
- 3 ≤ n ≤ 1018
- n does not have leading zeros
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given n = 13 (decimal)
2
Process
Find smallest base k where n = 111...1 in base k
3
Output
Base 3: 13 = 111₃ = 1×9 + 1×3 + 1×1
Key Takeaway
🎯 Key Insight: Use geometric series formula n = (k^m - 1)/(k - 1) to find the base mathematically
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code