Chat app~18 min2s · 256 MBtarget O(26 n) time, O(n) spacegreedy
You work on a chat app that shows a strip of stickers. Each sticker has a type, written as a lowercase letter. A strip looks bad when two stickers of the same type sit side by side, so the app reorders the stickers before showing them.
Your team lead asks: "Reorder the stickers so that no two neighbours are equal. If several orders work, use the smallest in dictionary order." The strip can hold up to 100,000 stickers.
Write spread_stickers(stickers).
stickers is a string of lowercase letters, one for each sticker.Input: stickers = "bananas"
Output: "abanans"At each position, choose the smallest letter that differs from the previous one, and that still lets the rest of the strip be finished.
| Position | Letter chosen |
|---|---|
| 1 | a |
| 2 | b |
| 3 | a |
| 4 | n |
| 5 | a |
| 6 | n |
| 7 | s |
Input: stickers = "aab"
Output: "aba"The letters a, a and b can only be arranged as a, b, a without two equal neighbours.
Input: stickers = "aaab"
Output: ""Three of the four stickers have type a. An a would have to sit between any two other letters, and there is only one other sticker, so the answer is the empty string.
1 ≤ len(stickers) ≤ 100,000stickers holds only the letters a to zYou cannot try the orders: even 12 different letters have 479,001,600 orders. A rule that picks each letter in a small, fixed number of steps is needed. With 26 possible letters, one check per letter at each of 100,000 positions is 2,600,000 checks, which is easily fast enough.