1182. Dictionary Letter Sort

Easy1.5 points estimatedCounting SortCustom ComparatorString

A library shelf label printer wants its characters in dictionary order, where each lowercase letter is immediately followed by its own capital. Given the string s made of ASCII letters and digits, rearrange its characters so that the order is a, A, b, B, ..., z, Z and then the digits 0 to 9.

Return the sorted string. Equal characters are simply grouped together, so a string such as "Ba2" becomes "aB2". Do not use a comparison sort: count how many times each of the 62 possible characters occurs and write them out bucket by bucket.

Constraints: 1 <= s.length <= 10^5 and s contains only ASCII letters and digits. A counting sort over 62 buckets runs in O(n) time with O(1) extra space apart from the output.

Example 1

Input:
s = "bAaB"
Output:
"aAbB"
Explanation:

The letters order as a, A, b, B, so "bAaB" sorts to "aAbB".

Example 2

Input:
s = "z9Zy0"
Output:
"yzZ09"
Explanation:

Letters come first as y, z, Z and the digits 9 and 0 follow in the order 0 then 9, giving yzZ09.

Constraints

1 ≤ s.length ≤ 105

s contains only ASCII letters and digits

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…