#2165

Smallest Value of the Rearranged Number

Medium
MathSortingSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n log n)
Space
O(n!)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution focuses on sorting the digits of the number. For positive numbers, we ensure the smallest non-zero digit is at the front, while for negative numbers, we sort the digits in descending order to maximize the value. This is efficient and avoids unnecessary permutations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Convert the number to a string to access its digits.
  2. 2Step 2: Separate the digits and sort them.
  3. 3Step 3: For positive numbers, find the smallest non-zero digit and place it at the front.
  4. 4Step 4: For negative numbers, simply reverse the sorted digits.
  5. 5Step 5: Convert the sorted array back to an integer.
solution.py19 lines
1# Full working Python code
2
3def smallest_rearranged_number(num):
4    str_num = str(num)
5    is_negative = str_num[0] == '-'
6    digits = sorted(str_num[1:] if is_negative else str_num)
7    if not is_negative:
8        # Move the smallest non-zero digit to the front
9        for i in range(len(digits)):
10            if digits[i] != '0':
11                digits[0], digits[i] = digits[i], digits[0]
12                break
13        return int(''.join(digits))
14    else:
15        return -int(''.join(digits[::-1]))
16
17# Example usage
18print(smallest_rearranged_number(310))  # Output: 103
19print(smallest_rearranged_number(-7605))  # Output: -7650

Complexity note: The time complexity is O(n log n) due to the sorting step, which is efficient compared to generating permutations. The space complexity is O(n) for storing the digits.

  • 1Sorting digits is a powerful technique for minimizing or maximizing numerical values.
  • 2Handling leading zeros is crucial for valid number formation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.