Taro Logo

Minimum Addition to Make Integer Beautiful

#24 Most AskedMedium
0 views
Topics:
Greedy AlgorithmsBit Manipulation

You are given two positive integers n and target.

An integer is considered beautiful if the sum of its digits is less than or equal to target.

Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.

Example 1:

Input: n = 16, target = 6
Output: 4
Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.

Example 2:

Input: n = 467, target = 6
Output: 33
Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.

Example 3:

Input: n = 1, target = 1
Output: 0
Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.

Constraints:

  • 1 <= n <= 1012
  • 1 <= target <= 150
  • The input will be generated such that it is always possible to make n beautiful.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the possible ranges for the input integers $n$ and $target$?
  2. Is it guaranteed that a valid integer $x$ always exists for any given inputs of $n$ and $target$?
  3. Can $target$ ever be larger than the sum of the digits of $n$, and if so, should the minimum addition $x$ be 0?
  4. What is the expected return type and maximum size for the resulting integer $n + x$? Could it potentially exceed standard integer limits?
  5. Are $n$ and $target$ always guaranteed to be positive integers, or could $n$ be zero?

Brute Force Solution

Approach

To solve this problem using a brute force approach, we can simply start by looking at our original number and checking if the sum of its digits is already small enough. If it is not, we can test adding one to our number repeatedly, checking the sum of the digits after each addition until we finally reach a number whose digit sum meets our goal.

Here's how the algorithm would work step-by-step:

  1. Take the starting number and separate it into its individual digits to add them together.
  2. Check if this sum is less than or equal to the maximum allowed limit.
  3. If the sum is already small enough, stop immediately because zero additions are needed.
  4. If the sum is too large, add one to the number.
  5. Repeat the process of separating the digits, adding them up, and checking the sum against the limit.
  6. Keep track of how many times you had to add one to the original number.
  7. Stop as soon as you find a number whose digit sum is within the allowed limit, and report the total amount you added.

Code Implementation

def make_integer_beautiful(original_number, target_limit):
    # We need to track how much we have added to reach our goal
    total_added_amount = 0

    current_number = original_number

    while True:
        digit_sum = sum(int(digit_character) for digit_character in str(current_number))

        # Stop immediately if our current digit sum is already small enough
        if digit_sum <= target_limit:
            return total_added_amount

        current_number += 1
        total_added_amount += 1

Big(O) Analysis

Time Complexity
O(t * log10(n)) – The time complexity is driven by the number of additions required to reach a beautiful integer, denoted as t, and the cost of computing the digit sum for each step. Since each increment and digit sum operation depends on the number of digits, which is proportional to log10(n), the process performs t checks. Multiplying the number of iterations t by the digit extraction cost log10(n) gives approximately t * log10(n) total operations. Depending on the distance to the next beautiful number, this simplifies in the worst case to O(t * log10(n)).
Space Complexity
O(log N) – The algorithm uses a few primitive variables to track the current number, the digit sum, and the total addition amount, without utilizing any dynamic data structures like arrays or hash maps. The number of digits in the input integer N dictates the maximum value of the intermediate calculations, but the auxiliary space consumed by these scalar variables remains constant. Therefore, the extra memory used does not scale with the size of N, resulting in constant auxiliary space complexity.

Optimal Solution

Approach

The optimal strategy works by looking at the digits of the number from right to left, similar to how we perform addition on paper. Whenever the sum of the digits exceeds the allowed limit, we bump up the value of the next digit to round up the number, which naturally forces the smaller digits to become zeros and reduces the overall sum.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the digits of the number, focusing on the ones place first.
  2. Add up all the digits in the number to check if the total sum is within the allowed limit.
  3. If the total sum is already small enough, no addition is needed and you are already done.
  4. If the total sum is too high, focus on the rightmost non-zero part and increase it to round up the number to the next clean place value, such as moving from tens to hundreds or hundreds to thousands.
  5. When you round up this way, all the digits to the right of your focus point turn into zeros, which dramatically drops the total sum of the digits.
  6. Keep repeating this rounding process, moving further to the left, until the sum of all digits finally drops to the allowed limit or below.
  7. Measure the difference between your newly modified rounded number and your original starting number to find the exact minimum addition needed.

Code Implementation

class Solution:
    def make_integer_beautiful(self, initial_number: int, target_sum: int) -> int:
        original_number = initial_number
        multiplier = 1

        # We calculate the sum of digits repeatedly until it satisfies the target constraint.
        while sum(int(digit) for digit in str(initial_number)) > target_sum:
            initial_number = (initial_number // (multiplier * 10) + 1) * (multiplier * 10)
            multiplier *= 10

        # The difference between the rounded number and original gives the minimum addition.
        return initial_number - original_number

Big(O) Analysis

Time Complexity
O(log10 n) – The input size is defined by the integer n, and the cost is driven by the number of decimal digits in n, which is proportional to log10 n. In each iteration of the rounding process, we increment the number and shift our focus one place value to the left, processing at most one digit per decimal place. Since the number of digits in n is bounded by log10 n, the loop runs at most log10 n times. This gives approximately log10 n operations, which simplifies to the Big O time complexity of O(log10 n).
Space Complexity
O(1) – The algorithm operates directly on numerical values using a few primitive integer variables to track the current number, the digit sum, and the rounding multiplier. No dynamic data structures like arrays, hash maps, or recursion stacks are utilized, meaning the memory consumption remains completely constant. As the input size N grows, the number of auxiliary variables stays fixed without scaling. Consequently, the total extra memory required simplifies to a constant space complexity of O(1).

Edge Cases

n is already beautiful where the sum of its digits is less than or equal to target
How to Handle:
The algorithm should immediately check this condition and return 0 as no addition is needed.
n and target are single-digit numbers
How to Handle:
A direct comparison handles this trivially by returning the difference or zero if already within target.
Maximum possible inputs where n is up to 10 to the power of 12 and target is small
How to Handle:
Using 64-bit integer types prevents overflow during iterative addition and digit sum calculations.
Trailing zeros in n causing cascading carries when adding x
How to Handle:
Incrementally rounding up n to the next power of 10 effectively clears trailing digits and generates carries correctly.
Target is very small like 1 while n is large
How to Handle:
The iterative carry propagation mechanism scales up the number place by place until the most significant digit satisfies the target sum.
n contains all nines leading to maximum possible digit sum
How to Handle:
The carry operation smoothly propagates across all nines, adding a leading one and resetting lower digits to zero.
Negative numbers or zero as inputs
How to Handle:
The problem constraints specify positive integers for n and target, but standard defensive programming validates inputs against non-positive values.
0/257 completed