LeetCode 2165: Smallest Value of the Rearranged Number Solution
Master LeetCode problem 2165 (Smallest Value of the Rearranged Number), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we need to rearrange the digits of the given number to form the smallest possible number without any leading zeros. We can achieve this by sorting the digits of the number in non-decreasing order, while ensuring that the most significant digit is not zero. If the original number is negative, we need to consider the sign while rearranging the digits.
Here is the high-level algorithm:
- Convert the absolute value of the input number to a list of digits.
- Sort the list of digits in non-decreasing order.
- If the original number was negative, swap the first digit (excluding 0 if present) with the last digit to maintain the sign.
- Convert the sorted list of digits back to a number.
The time complexity of this approach is O(n log n) where n is the number of digits in the input number, due to the sorting step. The space complexity is O(n) to store the list of digits.
Solution Code
class Solution {
public int rearrangeNumber(int num) {
if (num == 0) {
return 0;
}
boolean isNegative = num < 0;
num = Math.abs(num);
List<Integer> digits = new ArrayList<>();
while (num > 0) {
digits.add(num % 10);
num /= 10;
}
Collections.sort(digits);
if (isNegative) {
for (int i = 0; i < digits.size(); i++) {
if (digits.get(i) != 0) {
int temp = digits.get(i);
digits.set(i, digits.get(digits.size() - 1));
digits.set(digits.size() - 1, temp);
break;
}
}
}
int result = 0;
for (int digit : digits) {
result = result * 10 + digit;
}
return isNegative ? -result : result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2165 (Smallest Value of the Rearranged Number)?
This page provides optimized solutions for LeetCode problem 2165 (Smallest Value of the Rearranged Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2165 (Smallest Value of the Rearranged Number)?
The time complexity for LeetCode 2165 (Smallest Value of the Rearranged Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2165 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2165 in Java, C++, or Python.