1368. Largest Multiple of Six

Hard7.5 points estimatedCounting SortGreedyMathsString

A ticket printer holds a tray of digit tiles, given in the array digits with values from 0 to 9. It may pick any non-empty subset of the tiles, in any order, and print them side by side as a number. The ticket is valid only if the number is divisible by 6, that is, the digit sum is divisible by 3 and the last digit is even.

Return the largest valid number as a string. A number may not start with 0 unless it is exactly "0". Longer numbers are larger, and numbers of equal length compare as usual. If no valid number exists, return the empty string. Because the tray can hold 10^4 tiles, keep counts of the ten digit values, try keeping everything or removing one or two tiles, and build each candidate from the counts. Aim for O(n) time and O(n) space.

Example 1

Input:
digits = [8,6,7,1,0]
Output:
"8760"
Explanation:

Dropping the 1 leaves a digit sum of 21; arranging the rest as 8,7,6 and ending in the even 0 gives 8760, the largest valid number.

Example 2

Input:
digits = [1,1,1]
Output:
""
Explanation:

The sum is divisible by 3, but there is no even digit to end the number, so the answer is the empty string.

Example 3

Input:
digits = [0,0,0]
Output:
"0"
Explanation:

The only valid number is 0, because longer strings of zeros would start with 0.

Constraints

  • 1 ≤ digits.length ≤ 104

  • 0 ≤ digits[i] ≤ 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(n)

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…