2165. Smallest Value of the Rearranged Number

count sort

T: O(n), n is number's length

S: O(1)

class Solution {
    public long smallestNumber(long num) {
        // initialize frequency of each digit to Zero
        long[] freq = new long[10];

        // Checking Number is positive or Negative
        boolean isPositive = (num > 0);

        // Getting the absolute value of num
        num = Math.abs(num);
        
        // count frequency of each digit in the number
        while (num != 0){
            freq[(int)(num % 10)]++;
            num /= 10;
        }

        long result = 0;

        // If it is positive Number then it should be smallest
        if(isPositive) {
            // Set the LEFTMOST digit to minimum expect 0
            for (int i = 1; i <= 9; i++) {
                if (freq[i] != 0) {
                    result = i;
                    freq[i]--;
                    break;
                }
            }

            // arrange all remaining digits
            // in ascending order
            for (int i = 0; i <= 9; i++) {
                while (freq[i]-- != 0) {
                    result = result * 10 + i;
                }
            }
        // If negative then number should be Largest
        } else {
            //System.out.println("here");
            // Set the Rightmost digit to maximum
            for (int i = 9; i >= 1; i--) {
                
                if (freq[i] != 0) {
                    //System.out.println("i:"+i);
                    result = i;
                    freq[i]--;
                    break;
                }
            }

            // arrange all remaining digits
            // in descending order
            for (int i = 9; i >= 0; i--) {
                while (freq[i]-- != 0) {
                    result = result * 10 + i;
                }
            }

            // Negative number should be returned here
            result = -result;
        }
        return result;
    }
}

/*
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.

start from 1: asc
start from 1: desc

*/

sort

T: O(nlogn)

Last updated