Skip to main content

Smallest Formed Number

easy
Software engineer

Given an array of single-digit integers digits, your task is to use all elements of digits exactly once to form the smallest possible non-negative integer by concatenating the digits in any order.

The result must be returned as a string and should not contain any leading zeros unless the result itself is "0".

Note: You must use every digit from the input array.

Example 1

Input

digits = [8, 7, 1]

Output

"178"

Explanation

To form the smallest number, we sort the digits in ascending order: 1, 7, 8. Concatenating them results in "178". Since there are no leading zeros, this is the final answer.

Example 2

Input

digits = [0, 4, 0]

Output

"400"

Explanation

We must use all digits. Sorting gives [0, 0, 4]. However, leading zeros are not allowed. We find the smallest non-zero digit (4) and place it first, followed by the zeros: "400".

Example 3

Input

digits = [9, 1, 3, 9, 0, 0, 5]

Output

"1003599"

Explanation

Sorting the digits gives 0, 0, 1, 3, 5, 9, 9. To avoid leading zeros, we pick the smallest non-zero digit '1' to start, then place all other digits in ascending order: 1 -> 0, 0, 3, 5, 9, 9.

Constraints

  • 1 <= digits.length <= 10⁵
  • 0 <= digits[i] <= 9

Onsite

ArrayGreedySortingString
Language
Code editor loads in the browser.

Output

Input

[8,7,1]

Expected

"178"

Your output

Run to see your output.