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 = "3"
Output: "2"
💡 Note: 3 in base 2 is 11: 1×2¹ + 1×2⁰ = 2 + 1 = 3. This is the smallest base where 3 consists of all 1's.

Constraints

  • n is represented as a string
  • 3 ≤ n ≤ 1018
  • n does not have leading zeros

Visualization

Tap to expand
Smallest Good Base INPUT n = "13" Find smallest base k where n = 1 + k + k² + ... + k^m Goal: n in base k = 111...1 13 in base 3: 1×3² + 1×3¹ + 1×3⁰ = 9 + 3 + 1 = 13 Input Value: n = 13 ALGORITHM STEPS 1 Set bounds for m m = number of 1's - 1 Max m = log₂(n) 2 Try m from large to small Larger m means smaller k 3 Binary search for k For each m, find k where 1+k+k²+...+k^m = n 4 Verify and return First valid k found is the smallest good base For n=13, try m=2: k = floor(13^(1/2)) = 3 Check: 1 + 3 + 9 = 13 OK - Valid! FINAL RESULT Smallest Good Base Found k = 3 Verification: 13 in base 3 = 111 1×9 + 1×3 + 1×1 = 13 Output: "3" Key Insight: The equation 1 + k + k² + ... + k^m = n is equivalent to (k^(m+1) - 1)/(k - 1) = n. For a fixed m (number of digits minus 1), we can binary search for k. Since we want the smallest base, we try larger values of m first (more digits means smaller base). Time complexity: O(log²n) TutorialsPoint - Smallest Good Base | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen