KatInterview

483. Smallest Good Base

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Mathematical Derivation + Binary Search

This problem asks for the smallest base k >= 2 such that the representation of a number n in base k consists only of 1s. Let's analyze what this means mathematically.

Solution

Smallest Good Base in Python

class Solution:
    def smallestGoodBase(self, n: str) -> str:
        num_n = int(n)

        # The number of digits 'm' can range from 2 to about 60 (log2(10^18)).
        # We iterate m from high to low to find the smallest k.
        max_m = num_n.bit_length() # A good upper bound for m, equivalent to floor(log2(n))+1

        for m in range(max_m, 1, -1):
            # Determine the search range for base k.
            # k must be at least 2.
            low = 2
            # k is roughly n^(1/(m-1)). This is a tight upper bound for the search.
            high = int(num_n ** (1 / (m - 1)))

            if high < low:
                continue

            # Binary search for k in [low, high]
            while low <= high:
                k = (low + high) // 2
                
                # Calculate sum = 1 + k + ... + k^(m-1)
                # This is a geometric series sum: (k^m - 1) / (k - 1)
                # Python's integers handle arbitrary size, so no overflow.
                sum_val = (k**m - 1) // (k - 1)

                if sum_val == num_n:
                    return str(k)
                elif sum_val < num_n:
                    low = k + 1
                else: # sum_val > num_n
                    high = k - 1

        # Fallback for m=2 case: n = k + 1 => k = n - 1.
        # This is guaranteed to be a solution if no other is found.
        return str(num_n - 1)

Smallest Good Base in Java

import java.math.BigInteger;

class Solution {
    public String smallestGoodBase(String n) {
        BigInteger num_n = new BigInteger(n);

        // The number of digits 'm' can range from 2 to about 60 (log2(10^18)).
        // We iterate m from high to low to find the smallest k.
        int max_m = (int)(Math.log(Long.parseLong(n)) / Math.log(2)) + 1;

        for (int m = max_m; m >= 2; m--) {
            // Determine the search range for base k.
            // k must be at least 2.
            BigInteger low = BigInteger.valueOf(2);
            // k is roughly n^(1/(m-1)). We use this as an upper bound.
            // For integer roots, we can use a trick with nthRoot.
            // Let's find k = n^(1/(m-1)).
            // An estimate is sufficient for binary search boundary.
            BigInteger high = BigInteger.valueOf((long) Math.pow(num_n.doubleValue(), 1.0 / (m - 1)));

            // Binary search for k in [low, high+1]
            // Add one to high for safety due to double precision issues
            while (low.compareTo(high.add(BigInteger.ONE)) <= 0) {
                BigInteger k = low.add(high.subtract(low).divide(BigInteger.valueOf(2)));
                if (k.compareTo(BigInteger.valueOf(2)) < 0) { // Base must be >= 2
                   low = BigInteger.valueOf(2);
                   continue;
                }

                // Calculate sum = (k^m - 1) / (k - 1) using BigInteger
                BigInteger sum = k.pow(m).subtract(BigInteger.ONE).divide(k.subtract(BigInteger.ONE));
                
                int cmp = sum.compareTo(num_n);
                if (cmp == 0) {
                    return k.toString();
                } else if (cmp < 0) {
                    low = k.add(BigInteger.ONE);
                } else { // cmp > 0
                    high = k.subtract(BigInteger.ONE);
                }
            }
        }

        // Fallback for m=2 case: n = k + 1 => k = n - 1.
        return num_n.subtract(BigInteger.ONE).toString();
    }
}

Smallest Good Base in C++

class Solution {
public:
    string smallestGoodBase(string n) {
        unsigned long long num_n = stoull(n);

        // The number of digits 'm' can range from 2 to about 60.
        // We iterate m from high to low to find the smallest k.
        for (int m = 60; m >= 2; --m) {
            // Determine the search range for base k.
            // k must be at least 2.
            unsigned long long low = 2;
            // k is roughly n^(1/(m-1)). We can use this to set an upper bound.
            // pow function returns a double, there can be precision issues.
            // Add 1 for safety. Or just use num_n - 1 as a loose bound.
            unsigned long long high = (unsigned long long)pow(num_n, 1.0 / (m - 1)) + 1;
            
            if (high < low) {
                // The estimated upper bound might be less than 2 if m is very large.
                // For example n=13, m=4, high becomes pow(13, 1/3) ~ 2.35, cast to 2. 
                // If high=2, range is [2, 2], still valid. If high<2, continue.
                // Let's ensure high is at least 2.
                 high = 2; // to handle cases where pow result is less than 2.
            }
            
            // Binary search for k in [low, high]
            while (low <= high) {
                unsigned long long k = low + (high - low) / 2;
                if (k < 2) continue; // Base must be >= 2
                
                // Calculate sum = 1 + k + ... + k^(m-1)
                // Must handle overflow carefully.
                unsigned long long sum = 1;
                unsigned long long term = 1;
                bool overflow = false;
                for (int i = 1; i < m; ++i) {
                    // Check for overflow before multiplication term * k
                    if (num_n / k < term) { 
                        overflow = true;
                        break;
                    }
                    term *= k;
                    // Check for overflow before addition sum + term
                    if (num_n - term < sum) { 
                        overflow = true;
                        break;
                    }
                    sum += term;
                }

                if (overflow || sum > num_n) {
                    high = k - 1;
                } else if (sum < num_n) {
                    low = k + 1;
                } else { // sum == num_n
                    return to_string(k);
                }
            }
        }

        // Fallback for m=2 case: n = k + 1 => k = n - 1.
        // This loop structure guarantees we've already checked all m > 2,
        // so if we haven't returned, the only remaining option is for m=2.
        return to_string(num_n - 1);
    }
};

Smallest Good Base in TypeScript

function smallestGoodBase(n: string): string {
    const num_n = BigInt(n);

    // The number of digits 'm' can range from 2 to about 60 (log2(10^18)).
    // We iterate m from high to low to find the smallest k.
    // A safe upper bound for m is 64.
    for (let m = 60; m >= 2; m--) {
        // Determine the search range for base k.
        // k must be at least 2.
        let low = 2n;
        // k is roughly n^(1/(m-1)). We use this as an upper bound for binary search.
        // Since we can't do fractional exponents on BigInt, we use `Math.pow` on Number.
        // This might have precision issues but is good for an estimate.
        let high = BigInt(Math.floor(Math.pow(Number(n), 1.0 / (m - 1))));

        if (high < low) {
            continue;
        }

        // Binary search for k in [low, high]
        while (low <= high) {
            const k = low + (high - low) / 2n;
            if (k < 2n) continue; // Base must be >= 2

            // Calculate sum = 1 + k + ... + k^(m-1)
            // Using a loop to avoid potential floating point issues with the formula
            // and to perform early exit if the sum exceeds num_n.
            let sum = 1n;
            let term = 1n;
            let overflow = false;
            for (let i = 1; i < m; i++) {
                term *= k;
                sum += term;
                if (sum > num_n) { // Early exit if sum is already too large
                    overflow = true;
                    break;
                }
            }

            if (overflow) {
                high = k - 1n;
            } else if (sum < num_n) {
                low = k + 1n;
            } else { // sum === num_n
                return k.toString();
            }
        }
    }

    // Fallback for m=2 case: n = k + 1 => k = n - 1.
    return (num_n - 1n).toString();
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.