Teaching Kids Programming – Algorithm to Compute the Smallest Value of the Rearranged Number (Math)


Teaching Kids Programming: Videos on Data Structures and Algorithms

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

Hints:
For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order.
For negative numbers, the digits should be arranged in descending order.

Algorithm to Compute the Smallest Value of the Rearranged Number

Negative numbers, we just need to sort the digits in the decreasing order. For positive numbers, we sort the digits in the increasing order, then we need to find the first non-zero digit, and then we need to put it at the begining, and put zeros (digits before the index) next, and then put the remaining digits at the end.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def smallestNumber(self, num: int) -> int:
        if num == 0:
            return 0        
        if num < 0:
            s = list(str(-num))
            return int("-" + "".join(sorted(s, reverse=True)))
        else:
            s = list(str(num))
            s.sort()
            i = next(x for x, c in enumerate(s) if c != '0')
            return int(s[i] + "".join(s[:i] + s[i + 1:])) 
class Solution:
    def smallestNumber(self, num: int) -> int:
        if num == 0:
            return 0        
        if num < 0:
            s = list(str(-num))
            return int("-" + "".join(sorted(s, reverse=True)))
        else:
            s = list(str(num))
            s.sort()
            i = next(x for x, c in enumerate(s) if c != '0')
            return int(s[i] + "".join(s[:i] + s[i + 1:])) 

If there are N digits, the time complexity is O(NLogN) because we need to sort the digits.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
434 words
Last Post: Teaching Kids Programming - Proof of Logarithm Rules: log(ab)=log(a)+log(b) and log(a/b)=log(a)-log(b)
Next Post: Teaching Kids Programming - Turtle Graphics/Canvas Programming in Python

The Permanent URL is: Teaching Kids Programming – Algorithm to Compute the Smallest Value of the Rearranged Number (Math)

Leave a Reply