Smallest Value of the Rearranged Number - Problem

You are given an integer num. Your task is to rearrange the digits of this number to create the smallest possible value while ensuring there are no leading zeros.

The challenge is to find the optimal arrangement of digits that minimizes the numerical value. For example, if you have the number 310, you could arrange it as 013, 103, 130, 301, or 310. However, 013 has a leading zero, so the smallest valid arrangement is 103.

Important: The sign of the number remains unchanged after rearranging the digits. If the input is negative, the output should also be negative.

Goal: Return the rearranged number with the minimal absolute value, preserving the original sign.

Input & Output

example_1.py โ€” Basic Positive Number
$ Input: num = 310
โ€บ Output: 103
๐Ÿ’ก Note: The digits are 3, 1, 0. Arranging them in ascending order gives 013, but this has a leading zero. So we place the smallest non-zero digit (1) first, followed by the rest in ascending order: 103.
example_2.py โ€” Negative Number
$ Input: num = -7605
โ€บ Output: -7650
๐Ÿ’ก Note: For negative numbers, we want to minimize the absolute value by making it as large as possible. The digits are 7, 6, 0, 5. Arranging in descending order gives 7650, so the result is -7650.
example_3.py โ€” All Zeros
$ Input: num = -000
โ€บ Output: 0
๐Ÿ’ก Note: Special case: when the number is 0 (or consists only of zeros), the result is simply 0.

Constraints

  • -1015 โ‰ค num โ‰ค 1015
  • No leading zeros allowed in the result
  • The sign of the number must be preserved

Visualization

Tap to expand
Complete Rearrangement ProcessPositive Example: 43204320Sort0234Fix leading 020342034Negative Example: -4320-4320Sort desc4320Add - sign-4320Key Strategy:โ€ข Positive numbers: ascending order (avoid leading 0)โ€ข Negative numbers: descending order (maximize absolute value)โ€ข Time complexity: O(n log n) due to sorting
Understanding the Visualization
1
Separate Sign
Handle positive and negative numbers differently
2
Sort Digits
Arrange digits in ascending (positive) or descending (negative) order
3
Handle Leading Zeros
For positive numbers, move smallest non-zero digit to front
4
Construct Result
Build the final number and apply the original sign
Key Takeaway
๐ŸŽฏ Key Insight: The optimal strategy is to sort digits and handle positive/negative cases differently - ascending order for positive (with leading zero fix) and descending for negative numbers.
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 18
28.3K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen