Smallest Good Base - Problem
You're given a positive integer n represented as a string, and your task is to find the smallest good base of n.
What makes a base "good"? A base k (where k ≥ 2) is considered good for number n if when we convert n to base k, all digits are 1's.
For example, if n = 13, then base k = 3 is good because 13 in base 3 is "111" (since 1×3² + 1×3¹ + 1×3⁰ = 9 + 3 + 1 = 13).
Goal: Return the smallest such base k as a string.
Input & Output
example_1.py — Basic case
$
Input:
n = "13"
›
Output:
"3"
💡 Note:
13 in base 3 is "111" because 1×3² + 1×3¹ + 1×3⁰ = 9 + 3 + 1 = 13. Base 3 is the smallest base where all digits are 1.
example_2.py — Larger number
$
Input:
n = "4681"
›
Output:
"8"
💡 Note:
4681 in base 8 is "11111" because 1×8⁴ + 1×8³ + 1×8² + 1×8¹ + 1×8⁰ = 4096 + 512 + 64 + 8 + 1 = 4681.
example_3.py — Edge case
$
Input:
n = "3"
›
Output:
"2"
💡 Note:
3 in base 2 is "11" because 1×2¹ + 1×2⁰ = 2 + 1 = 3. Base 2 is the smallest good base.
Constraints
- n is represented as a string
- 1 ≤ n ≤ 1018
- n is guaranteed to have at least one good base
- The answer will fit in a 64-bit signed integer
Visualization
Tap to expand
Understanding the Visualization
1
Identify the pattern
A number with all 1's in base k follows the pattern: 1 + k + k² + k³ + ...
2
Use geometric series formula
This sum equals (k^m - 1)/(k - 1) where m is the number of digits
3
Binary search optimization
For each possible m, binary search for k that satisfies the equation
Key Takeaway
🎯 Key Insight: Transform the digit-checking problem into a mathematical equation, then use binary search to efficiently find the solution in O(log²n) time instead of O(n).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code