1329. Smallest Digit Arrangement

Easy1.5 points estimatedCounting SortStringGreedy

A locksmith has a string digits made only of the characters 0 to 9 and must use every one of them exactly once to build the smallest possible number. The number may not start with the digit 0, unless every character of digits is 0, in which case the answer is the single character "0". Return the result as a string.

Count how often each digit occurs. Put the smallest non-zero digit first, then write all remaining digits in ascending order, zeros first. The string may have up to 1000 characters, so the answer is returned as text, never as a number. Expected O(n + 10) time and O(10) extra space apart from the output.

Example 1

Input:
digits = "30102"
Output:
"10023"
Explanation:

The digits are 0, 0, 1, 2, 3; start with the smallest non-zero digit 1, then 0, 0, 2, 3, giving 10023.

Example 2

Input:
digits = "000"
Output:
"0"
Explanation:

Every digit is 0, so the answer is the single character "0".

Example 3

Input:
digits = "5"
Output:
"5"
Explanation:

A single digit has only one arrangement.

Constraints

  • 1 ≤ digits.length ≤ 1000
  • digits contains only the characters '0' to '9'

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…