Smallest Value of the Rearranged Number

Medium
549.

Smallest Value of the Rearranged Number

Smallest Value of the Rearranged Number is a medium coding problem on math and sorting, asked in Amazon and Adobe interviews.

You are given an integer num. Rearrange its digits to produce the smallest possible value, keeping the sign of num.

The result must not have leading zeros.

Example 1

Input
num = 310
Output
103
Explanation
The rearrangements without a leading zero are 103, 130, 301, 310.

Example 2

Input
num = -7605
Output
-7650
Explanation
For a negative number, the largest digit arrangement gives the smallest value.

Example 3

Input
num = 0
Output
0

Constraints

  • -999999999 <= num <= 999999999
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {number} num
 * @return {number}
 */
var smallestNumber = function(num) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Smallest Value of the Rearranged Number — Problem & Solution

Smallest Value of the Rearranged Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem.

Smallest Value of the Rearranged Number is a medium coding problem on math and sorting, asked in Amazon and Adobe interviews.

  • Difficulty: Medium
  • Topics: Math, Sorting
  • Asked at: Amazon, Adobe
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

You are given an integer num. Rearrange its digits to produce the smallest possible value, keeping the sign of num.

The result must not have leading zeros.

Example 1

Input: num = 310
Output: 103
Explanation: The rearrangements without a leading zero are 103, 130, 301, 310.

Example 2

Input: num = -7605
Output: -7650
Explanation: For a negative number, the largest digit arrangement gives the smallest value.

Example 3

Input: num = 0
Output: 0

Constraints

  • -999999999 <= num <= 999999999

Hints for Smallest Value of the Rearranged Number

  1. Hint 1

    Handle the sign first, then work with the digits of |num|.

  2. Hint 2

    For a negative number, the smallest value comes from the largest digit arrangement — sort descending.

  3. Hint 3

    For a positive number sort ascending, then swap the leading zero with the first non-zero digit.

How to solve Smallest Value of the Rearranged Number

The sign flips the objective. For negatives, maximising the magnitude minimises the value; for positives, minimising the magnitude does — subject to the no-leading-zero rule.

Approach

  1. Return 0 immediately for num == 0.
  2. Take the digits of |num|.
  3. If num < 0, sort descending and negate the result — a leading zero cannot occur unless every digit is zero.
  4. If num > 0, sort ascending; if the first digit is 0, swap it with the first non-zero digit.
  5. Return the assembled number.

Why it works

Comparing two arrangements of the same multiset digit by digit, the smaller leading digit wins — so ascending order is optimal for positives, except that a leading zero is forbidden, and swapping in the smallest non-zero digit is the least damaging repair.

Complexity

  • Time — O(d log d) in the digit count
  • Space — O(d)

Pitfalls

  • Sorting ascending for a negative number gives the largest value, not the smallest.
  • Sorting ascending for a positive number with a zero digit produces a leading zero, e.g. 310 → 013.
  • The swap must target the first non-zero digit, not simply index 1.

Reference solution

Python

def smallestNumber(num: int) -> int:
    if num == 0:
        return 0
    neg = num < 0
    digits = sorted(str(abs(num)))
    if neg:
        digits.sort(reverse=True)
        return -int(''.join(digits))
    i = 0
    while i < len(digits) and digits[i] == '0':
        i += 1
    if i > 0 and i < len(digits):
        digits[0], digits[i] = digits[i], digits[0]
    return int(''.join(digits))

Java

public static int smallestNumber(int num) {
    if (num == 0) return 0;
    boolean neg = num < 0;
    char[] digits = Integer.toString(Math.abs(num)).toCharArray();
    Arrays.sort(digits);
    if (neg) {
        StringBuilder sb = new StringBuilder(new String(digits)).reverse();
        return -Integer.parseInt(sb.toString());
    }
    int i = 0;
    while (i < digits.length && digits[i] == '0') i++;
    if (i > 0 && i < digits.length) {
        char t = digits[0];
        digits[0] = digits[i];
        digits[i] = t;
    }
    return Integer.parseInt(new String(digits));
}

C++

int smallestNumber(int num) {
    if (num == 0) return 0;
    bool neg = num < 0;
    string digits = to_string(neg ? -(long long) num : (long long) num);
    sort(digits.begin(), digits.end());
    if (neg) {
        reverse(digits.begin(), digits.end());
        return -stoi(digits);
    }
    size_t i = 0;
    while (i < digits.size() && digits[i] == '0') i++;
    if (i > 0 && i < digits.size()) swap(digits[0], digits[i]);
    return stoi(digits);
}

JavaScript

var smallestNumber = function(num) {
    if (num === 0) return 0;
    const neg = num < 0;
    const digits = String(Math.abs(num)).split("").map(Number);
    if (neg) {
        digits.sort(function(a, b) { return b - a; });
        return -Number(digits.join(""));
    }
    digits.sort(function(a, b) { return a - b; });
    let i = 0;
    while (i < digits.length && digits[i] === 0) i++;
    if (i > 0 && i < digits.length) {
        const t = digits[0];
        digits[0] = digits[i];
        digits[i] = t;
    }
    return Number(digits.join(""));
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 337 math problems · the whole catalogue

Learn the technique: Sorting Algorithms