Skip to content
Problem 483 · LeetCode 483(opens in a new tab)

Smallest Good Base

HardBinary search

You get a positive whole number n, written as a decimal string. A base k ≥ 2 is good for n when n written in base k uses only the digit 1, like 111 or 11111.

Return the smallest good base of n, as a string.

Example 1

Input:  n = "40"
Output: "3"
Why:    1 + 3 + 9 + 27 = 40, so 40 is 1111 in base 3
2 more examples and the constraints

Example 2

Input:  n = "57"
Output: "7"
Why:    1 + 7 + 49 = 57, so 57 is 111 in base 7

Example 3

Input:  n = "10"
Output: "9"
Why:    only base 9 works: 10 is 11 in base 9

Constraints

  • 3 ≤ n ≤ 10¹⁸
  • n has no leading zeros

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. One candidate per digit countO(log² n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 10¹⁸Verdict
Binary search per digit countO(log³ n)
Passes; safe and exact
One candidate per digit countO(log² n)
Best; one root per length

n = the input number; log n is about 60. Trying every base is not listed: it can take 10¹⁸ steps.

Edge cases to test

  • Only two digits work. "10" has no long form, so the answer is n − 1 = 9.
  • All ones in binary. "15" is 1111 in base 2, the smallest base there is.
  • Largest n. With n = 10¹⁸ the sums leave 64 bits fast; guard against overflow.
  • Smallest n. "3" is 11 in base 2.

Common mistakes

  • Looping over every base, which needs up to 10¹⁸ steps.
  • Letting 1 + k + k² + … overflow 64 bits during the binary search.
  • Trying digit counts from small to large, which finds the largest good base first.

How to talk through it

  1. 1Clarify. n arrives as a string up to 10¹⁸; the answer is a string too.
  2. 2Flip the search. The base is huge, but the number of digits is at most 60. Loop over that.
  3. 3Pin down the base. For m digits, k is between the (m−1)-th root of n and that plus one, so there is one candidate.
  4. 4Code it with exact checks. Compute the candidate, verify the sum in integers, fall back to n − 1.
  5. 5Test out loud. Run "3", "15" and 10¹⁸.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?