Smallest Value of the Rearranged Number - 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: The sign of the number does not change after rearranging the digits.

Input & Output

Example 1 — Positive Number with Zero
$ Input: num = 4320
Output: 2034
💡 Note: Sort digits [4,3,2,0] → [0,2,3,4]. Since 0 is first, swap with first non-zero (2) → [2,0,3,4] = 2034
Example 2 — Negative Number
$ Input: num = -4320
Output: -2034
💡 Note: Same rearrangement as positive case, but keep negative sign: -2034
Example 3 — Single Digit
$ Input: num = 0
Output: 0
💡 Note: Single digit 0 remains 0

Constraints

  • -231 ≤ num ≤ 231 - 1

Visualization

Tap to expand
Smallest Value of the Rearranged Number INPUT Original Number 4 3 2 0 pos 0 pos 1 pos 2 pos 3 Input Details num = 4320 Type: Positive integer Digits: [4, 3, 2, 0] Constraints No leading zeros allowed Sign must be preserved Find minimum value ALGORITHM STEPS 1 Extract Digits Split: 4, 3, 2, 0 2 Sort Ascending Result: 0, 2, 3, 4 [4,3,2,0] --> sort [0,2,3,4] 3 Handle Leading Zero First digit is 0! 0234 invalid - leading zero Swap 0 with first non-zero 4 Swap and Build [0,2,3,4] --> [2,0,3,4] Result: 2034 FINAL RESULT Rearranged Number 2 0 3 4 Output 2034 Verification Original: 4320 Result: 2034 No leading zero: OK Minimum value: OK 2034 < 4320 Key Insight: For positive numbers, sort digits ascending for minimum value. If first digit is 0, swap it with the smallest non-zero digit to avoid leading zeros. For negative numbers, sort descending (larger absolute value = smaller negative). Time: O(n log n), Space: O(n) TutorialsPoint - Smallest Value of the Rearranged Number | Optimal Solution
Asked in
Amazon 25 Microsoft 18 Google 15
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen