Chat app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-791sorting
A chat app records the delivery status of each message as one lowercase letter, such as s for sent or r for read. A support screen shows the letters in an order chosen by the support team. That order is a string of distinct letters, from first to last. Letters that are not in the order go after all the others, in alphabetical order.
Write sort_by_status_order(text, order).
text is a string of lowercase letters, one for each message.order is a string of distinct lowercase letters, from first to last.text rearranged so the letters in order come first, in that order, with all copies together. Then come the other letters in alphabetical order.Input: text = "refreshed", order = "hre"
Output: "hrreeedfs"Write the letters of order first, each as many times as it appears in text. Then write the remaining letters from a to z.
| Step | Letter | Count | Written |
|---|---|---|---|
| rank order | h | 1 | h |
| rank order | r | 2 | rr |
| rank order | e | 3 | eee |
| left over, a to z | d | 1 | d |
| left over, a to z | f | 1 | f |
| left over, a to z | s | 1 | s |
The result is "hrreeedfs".
Input: text = "abc", order = "cba"
Output: "cba"All three letters are in the order, so the result is "cba".
Input: text = "zzxy", order = "q"
Output: "xyzz"No letter of text is in the order, so all go alphabetically: "xyzz".
0 ≤ text.length ≤ 100,000 (messages)1 ≤ order.length ≤ 26, with no letter repeated in order.a to z.There are only 26 different letters. Counting each letter once costs n, and writing the result costs n, so no comparison sort is needed.