Similar Problems

Similar Problems not available

Smallest Good Base - Leetcode Solution

Companies:

LeetCode:  Smallest Good Base Leetcode Solution

Difficulty: Hard

Topics: math binary-search  

The Smallest Good Base problem is a mathematics problem that requires one to find the smallest base of a number in which that number expresses as a sum of its digits in that base.

For example, if we have the number "13", then we can represent it in base "3" as "111", which is equal to 1 + 1 + 1 = 3. Here, "3" is the smallest possible base that makes "13" a good base representation.

Algorithm: To solve this problem, we can use a binary search approach. We will iterate through all possible bases starting from "2" and going up to a maximum possible base. At each iteration, we will calculate the sum of the digits of the number in that base. If the sum of the digits equals the original number, we have found the smallest good base. If not, we will update our search range and continue the binary search.

Here are the steps of this algorithm:

  1. Initialize the minimum and maximum base ranges. The minimum base will be "2", and the maximum base will be set to log2(n) + 1, where "n" is the input number.

  2. Using a binary search approach, iterate through all possible bases between the minimum and maximum base ranges.

  3. At each iteration, calculate the sum of the digits of the number in the current base.

  4. If the sum is equal to the original number, return the current base as the smallest good base.

  5. If the sum is less than the original number, update the minimum base range to current base + 1.

  6. If the sum is greater than the original number, update the maximum base range to current base - 1.

  7. Repeat steps from 2 to 6 until we find the smallest good base or the range becomes invalid.

Here is the Python code implementation of the above algorithm:

class Solution: def smallestGoodBase(self, n: str) -> str: n = int(n) max_base = int(math.log2(n)) + 1

    for base in range(max_base, 1, -1):
        lo, hi = 2, n-1
        while lo <= hi:
            mid = (lo + hi) // 2
            sum = self.calculateSum(mid, base)
            
            if sum == n:
                return str(mid)
            elif sum < n:
                lo = mid + 1
            else:
                hi = mid - 1
    
    return str(n-1)

def calculateSum(self, num, base):
    sum = 0
    for i in range(32):
        if num >> i & 1:
            sum += base ** i
    return sum

To summarize, the above algorithm uses binary search to find the smallest good base for a given number. We first set the minimum and maximum base ranges and then iterate through all possible bases within that range using binary search. At each iteration, we calculate the sum of digits of the number in that base and update the search range until we find the smallest good base or the range becomes invalid.

Smallest Good Base Solution Code

1