Problem

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.

Examples

Example 1

1
2
3
4
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

1
2
3
4
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

Method 1 – Sort Digits by Sign

Intuition

To minimize the value, rearrange the digits in ascending order for positive numbers (skipping leading zeros), and in descending order for negative numbers (to get the largest absolute value, which is the smallest negative). Handle zeros carefully to avoid leading zeros in the result.

Approach

  1. If the number is zero, return zero.
  2. For positive numbers:
    • Convert to string, sort digits in ascending order.
    • Move the first non-zero digit to the front to avoid leading zeros.
  3. For negative numbers:
    • Convert to string, sort digits in descending order.
    • Prepend ‘-’ to the result.
  4. Return the integer value of the rearranged string.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    long long smallestNumber(long long num) {
        if (num == 0) return 0;
        string s = to_string(abs(num));
        if (num > 0) {
            sort(s.begin(), s.end());
            int i = 0;
            while (i < s.size() && s[i] == '0') ++i;
            if (i < s.size()) swap(s[0], s[i]);
            return stoll(s);
        } else {
            sort(s.rbegin(), s.rend());
            return -stoll(s);
        }
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func smallestNumber(num int64) int64 {
    if num == 0 { return 0 }
    s := []byte(strconv.FormatInt(abs(num), 10))
    if num > 0 {
        sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
        i := 0
        for i < len(s) && s[i] == '0' { i++ }
        if i < len(s) { s[0], s[i] = s[i], s[0] }
        ans, _ := strconv.ParseInt(string(s), 10, 64)
        return ans
    } else {
        sort.Slice(s, func(i, j int) bool { return s[i] > s[j] })
        ans, _ := strconv.ParseInt(string(s), 10, 64)
        return -ans
    }
}
func abs(x int64) int64 { if x < 0 { return -x }; return x }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public long smallestNumber(long num) {
        if (num == 0) return 0;
        char[] arr = Long.toString(Math.abs(num)).toCharArray();
        if (num > 0) {
            Arrays.sort(arr);
            int i = 0;
            while (i < arr.length && arr[i] == '0') i++;
            if (i < arr.length) {
                char t = arr[0]; arr[0] = arr[i]; arr[i] = t;
            }
            return Long.parseLong(new String(arr));
        } else {
            Arrays.sort(arr);
            for (int l = 0, r = arr.length - 1; l < r; l++, r--) {
                char t = arr[l]; arr[l] = arr[r]; arr[r] = t;
            }
            return -Long.parseLong(new String(arr));
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    fun smallestNumber(num: Long): Long {
        if (num == 0L) return 0L
        val s = Math.abs(num).toString().toCharArray()
        if (num > 0) {
            s.sort()
            var i = 0
            while (i < s.size && s[i] == '0') i++
            if (i < s.size) s[0] = s[i].also { s[i] = s[0] }
            return String(s).toLong()
        } else {
            s.sortDescending()
            return -String(s).toLong()
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def smallestNumber(self, num: int) -> int:
        if num == 0: return 0
        s = list(str(abs(num)))
        if num > 0:
            s.sort()
            i = 0
            while i < len(s) and s[i] == '0': i += 1
            if i < len(s): s[0], s[i] = s[i], s[0]
            return int(''.join(s))
        else:
            s.sort(reverse=True)
            return -int(''.join(s))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
impl Solution {
    pub fn smallest_number(num: i64) -> i64 {
        if num == 0 { return 0; }
        let mut s: Vec<char> = num.abs().to_string().chars().collect();
        if num > 0 {
            s.sort();
            let mut i = 0;
            while i < s.len() && s[i] == '0' { i += 1; }
            if i < s.len() { s.swap(0, i); }
            s.into_iter().collect::<String>().parse().unwrap()
        } else {
            s.sort_by(|a, b| b.cmp(a));
            -s.into_iter().collect::<String>().parse::<i64>().unwrap()
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    smallestNumber(num: number): number {
        if (num === 0) return 0;
        let s = Math.abs(num).toString().split("");
        if (num > 0) {
            s.sort();
            let i = 0;
            while (i < s.length && s[i] === '0') i++;
            if (i < s.length) [s[0], s[i]] = [s[i], s[0]];
            return parseInt(s.join(""));
        } else {
            s.sort((a, b) => b.localeCompare(a));
            return -parseInt(s.join(""));
        }
    }
}

Complexity

  • ⏰ Time complexity: O(d log d), where d is the number of digits in num. Sorting the digits dominates.
  • 🧺 Space complexity: O(d), for storing the digits as a list or array.