Taro Logo

Smallest Value of the Rearranged Number

#1 Most AskedMedium
1 view
Topics:
ArraysGreedy Algorithms

You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.

Return the rearranged number with minimal value.

Note that the sign of the number does not change after rearranging the digits.

Example 1:

Input: num = 310
Output: 103
Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. 
The arrangement with the smallest value that does not contain any leading zeros is 103.

Example 2:

Input: num = -7605
Output: -7650
Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.
The arrangement with the smallest value that does not contain any leading zeros is -7650.

Constraints:

  • -1015 <= num <= 1015

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 is the exact range and data type of the input `num`? Could it exceed standard 32-bit integer limits (e.g., fit within a 64-bit integer or require string manipulation)?
  2. How should we handle a single-digit input, such as `0`, or negative numbers consisting of a single digit, like `-5`?
  3. For negative numbers, does the problem imply we should form the largest possible absolute value (which translates to the maximum mathematical value, e.g., sorting descending like `-76` instead of `-67`), and how should any potential leading zeros be handled for negative numbers?
  4. If the input integer contains multiple zeros (e.g., `3100`), should all zeros be placed immediately after the first non-zero digit to form the smallest valid number, or do they follow standard digit placement rules?
  5. Should the function return the result as a primitive integer type (like `long long` in C++ or `long` in Java/Python), or is returning a string representation preferred to prevent overflow issues during rearrangement?

Brute Force Solution

Approach

To solve this problem using the brute force approach, you examine every single possible way to rearrange the digits of the given number. After generating all of these different number combinations, you look through them to find the smallest valid one.

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

  1. Begin by taking all the individual digits that make up the starting number.
  2. Generate every possible combination by shuffling these digits into all conceivable orders.
  3. Filter out any combinations where a zero incorrectly ends up at the very front, since standard numbers cannot start with leading zeros.
  4. Examine all the remaining valid numbers you just created.
  5. Compare every single one of these valid numbers against each other.
  6. Select and declare the smallest number from your group of valid possibilities as the final answer.

Code Implementation

import itertools


def smallest_number(input_number):
    number_string = str(input_number)
    is_negative_number = number_string.startswith('-')

    if is_negative_number:
        digit_characters = list(number_string[1:])
        all_permutations = list(itertools.permutations(digit_characters))
        valid_numeric_values = []

        # We generate all digit permutations to evaluate every single possible rearrangement combination
        for current_permutation in all_permutations:
            reconstructed_value = "".join(current_permutation)
            if reconstructed_value[0] == '0':
                continue
            valid_numeric_values.append(-int(reconstructed_value))

        return min(valid_numeric_values)
    else:
        digit_characters = list(number_string)
        all_permutations = list(itertools.permutations(digit_characters))
        valid_numeric_values = []

        # We generate all digit permutations to evaluate every single possible rearrangement combination
        for current_permutation in all_permutations:
            reconstructed_value = "".join(current_permutation)

            # Leading zeros violate standard integer formatting rules so we must filter them out
            if len(reconstructed_value) > 1 and reconstructed_value[0] == '0':
                continue

            valid_numeric_values.append(int(reconstructed_value))

        # Finding the minimum value among valid permutations gives us the optimal rearranged result
        return min(valid_numeric_values)

Big(O) Analysis

Time Complexity
O(d * d!) – Here the input size d represents the number of digits in the given integer. Generating every possible permutation of these digits requires examining d factorial orders, and for each of these d! permutations, validating and assembling the number takes linear time proportional to d. Multiplying these operations together yields approximately d * d! steps, which simplifies to the factorial time complexity of O(d * d!).
Space Complexity
O(N!) – To find the smallest rearranged number using the brute force approach, we generate every possible combination of the digits. If we let N represent the total number of digits in the given number, generating permutations requires storing N factorial distinct combinations in memory. The auxiliary storage holds up to N! valid and invalid numbers simultaneously to compare them against each other. Consequently, the extra memory required grows factorially with the number of digits. Therefore, the overall space complexity simplifies in Big O notation to O(N!).

Optimal Solution

Approach

To find the smallest possible value after rearranging the digits of a number, we must handle positive and negative numbers differently since signs change how magnitude works. For positive numbers, the goal is to place the smallest non-zero digit at the very front to keep the number as small as possible, followed by the rest of the digits in increasing order. For negative numbers, we want to create the largest possible absolute value by arranging the digits in descending order and then applying the negative sign.

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

  1. Determine if the starting number is zero, positive, or negative, because zero simply remains zero and negative numbers require a completely different strategy than positive ones.
  2. If the number is positive, collect all of its individual digits and sort them from smallest to largest.
  3. Look at the sorted digits and find the very first non-zero digit, moving it to the absolute front of the sequence so that leading zeros are avoided.
  4. Place all the remaining zeros right after that first leading digit to keep the overall value as small as possible.
  5. Append the rest of the digits in ascending order to complete the positive number arrangement.
  6. If the number is negative, collect its digits and sort them from largest to smallest to create the largest possible magnitude.
  7. Place a negative sign in front of this descending sequence of digits to transform it into the smallest possible negative value.

Code Implementation

class Solution:
    def smallest_number(self, input_number: int) -> int:
        if input_number == 0:
            return 0

        # Positive and negative numbers require opposite sorting strategies to achieve extrema.
        if input_number > 0:
            digit_characters = sorted(list(str(input_number)))
            first_non_zero_index = next(index for index, digit_char in enumerate(digit_characters) if digit_char != '0')
            
            # Moving the first non-zero digit to the front prevents invalid leading zeros.
            rearranged_digits = [digit_characters[first_non_zero_index]] + digit_characters[:first_non_zero_index] + digit_characters[first_non_zero_index + 1:]
            return int("".join(rearranged_digits))
        else:
            # Descending order on negative numbers maximizes magnitude, yielding the smallest value.
            absolute_digit_chars = sorted(list(str(-input_number)), reverse=True)
            return -int("".join(absolute_digit_chars))

Big(O) Analysis

Time Complexity
O(d log d) – The primary cost driving the time complexity is extracting the digits of the input number and sorting them. If we let d represent the number of digits in the input value, converting the number to a collection of digits takes O(d) time. Sorting these d digits in ascending or descending order dominates the process, taking O(d log d) time. Rearranging the digits and reconstructing the final integer takes additional linear time proportional to the number of digits, which is O(d). Since the number of digits d is bound by the logarithmic value of the input n (specifically d is roughly proportional to log10(n)), the total operations scale with the number of digits, simplifying overall to O(d log d).
Space Complexity
O(D) – To handle the rearrangement, the algorithm converts the number into a string of its digits to collect them into an array or list, where D represents the number of digits in the input. Storing these individual digits requires auxiliary memory proportional to the length of the digit string. Additional scalar variables are used for loops, indices, and sorting, which require constant extra space. Therefore, the total auxiliary space complexity is driven by storing the digits and scales linearly with the number of digits D.

Edge Cases

Single digit numbers
How to Handle:
Return the number as is since no rearrangement is possible.
Negative numbers
How to Handle:
Sort the digits in descending order to form the maximum possible absolute value and preserve the negative sign.
Numbers with leading zeros in positive permutation
How to Handle:
Find the first non-zero digit, place it at the front, and insert all zeros immediately after it.
Zero as an input
How to Handle:
Return zero directly without any modification.
All identical digits
How to Handle:
Return the number as is since sorting yields the exact same value.
Integer overflow beyond 64-bit limits during rearrangement
How to Handle:
Use string manipulation or standard 64-bit integer types to safely construct and parse the result.
0/1 completed