Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2165: Smallest Value of the Rearranged Number

In this guide, we solve Leetcode #2165 Smallest Value of the Rearranged Number in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Math, Sorting

Intuition

Sorting reveals structure that is hard to see in the original order.

Once sorted, a linear scan is usually enough to compute the answer.

Approach

Sort the data and sweep through it while maintaining a small state.

This keeps the logic straightforward and reliable.

Steps:

  • Sort the data.
  • Scan in order while maintaining state.
  • Update the best answer.

Example

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.

Python Solution

class Solution: def smallestNumber(self, num: int) -> int: neg = num < 0 num = abs(num) cnt = [0] * 10 while num: cnt[num % 10] += 1 num //= 10 ans = 0 if neg: for i in reversed(range(10)): for _ in range(cnt[i]): ans *= 10 ans += i return -ans if cnt[0]: for i in range(1, 10): if cnt[i]: ans = i cnt[i] -= 1 break for i in range(10): for _ in range(cnt[i]): ans *= 10 ans += i return ans

Complexity

The time complexity is O(log⁡n)O(\log n)O(logn), where nnn is the size of the number num\textit{num}num. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy