1339. Smallest Joined Number

Medium3.5 points estimatedCustom ComparatorStringGreedySorting

A kiosk prints a ticket number by gluing together all the numbers in nums, each used exactly once and written in decimal, in an order you choose. Return the smallest possible ticket as a string. A ticket may not start with a zero, except that when every value in nums is 0 the answer is the single digit "0". All tickets have the same length, so the smallest one is also the lexicographically smallest string. A pairwise rule helps: place a before b when a followed by b is smaller than b followed by a. Because a zero cannot lead, try each distinct non-zero value as the first piece and add the rest in rule order, then keep the smallest result. Aim for O(n^2 * L) time where L is the digit length.

Example 1

Input:
nums = [12,121,5]
Output:
"121125"
Explanation:

Gluing 121, then 12, then 5 gives 121125, the smallest ticket without a leading zero.

Example 2

Input:
nums = [0,0,7,0]
Output:
"7000"
Explanation:

The zeros cannot lead, so 7 goes first and the three zeros follow, giving 7000.

Example 3

Input:
nums = [3,301,0,50,30]
Output:
"300301350"
Explanation:

Starting with 30 gives 300301350, smaller than starting with 3 (303013050), 301 or 50; a leading 0 is not allowed.

Constraints

1 ≤ n ≤ 100

0 ≤ nums[i] ≤ 109

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^2 * L)
Space
O(n * L)

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…