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
Geometric Series Visualization: n = 1313⁰ = 133¹ = 393² = 9=13Sum++Mathematical FormulaGeometric Series Sum1 + k + k² + ... + k^(m-1) = (k^m - 1)/(k - 1)For our case: (3³ - 1)/(3 - 1) = 26/2 = 13 ✓Binary Search Strategy1. Try different values of m (number of digits)2. For each m, binary search for k that satisfies the equation3. Return the smallest valid k found
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).
Asked in
Google 35 Facebook 25 Amazon 20 Microsoft 15
28.5K Views
Medium Frequency
~25 min Avg. Time
842 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