Skip to main content

Smallest Value of the Rearranged Number

LeetCode 2284 | Difficulty: Medium​

Medium

Problem Description​

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:

- `-10^15 <= num <= 10^15`

Topics: Math, Sorting


Approach​

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.

Sorting​

Sort the input to bring related elements together or enable binary search. Consider: does sorting preserve the answer? What property does sorting give us?

When to use

Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.


Solutions​

Solution 1: C# (Best: 26 ms)​

MetricValue
Runtime26 ms
Memory25.3 MB
Date2022-02-13
Solution
public class Solution {
public long SmallestNumber(long num) {
int[] freq = new int[10];
long n = num;
bool isNeg = false;
if(n<0)
{
isNeg = true;
n = n * -1;
}
while(n>0)
{
freq[n%10]++;
n = n/10;
}
long result = 0;

if (!isNeg)
{
for (int i = 1; i < 10; i++)
{
if (freq[i] > 0)
{
result = result * 10 + i;
freq[i]--;
break;
}
}
while(freq[0]>0)
{
result = result * 10 + 0;
freq[0]--;
}
for (int i = 1; i < 10; i++)
{
while (freq[i] > 0)
{
result = result * 10 + i;
freq[i]--;
}
}

}
else
{
for (int i = 9; i >= 0; i--)
{
while (freq[i] > 0)
{
result = result * 10 + i;
freq[i]--;
}
}
result = result * -1;

}
return result;
}
}

Complexity Analysis​

ApproachTimeSpace
Sort + Process$O(n log n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • LeetCode provides 2 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order.

Hint 2: For negative numbers, the digits should be arranged in descending order.