text of lowercase English letters. Rearrange its letters so that no two neighbouring letters are equal. If that is impossible, return the empty string "".
There are usually many valid arrangements, so build this particular one:
1. Line the letters up in a queue: first every copy of the most frequent letter, then the next most frequent, and so on. Letters that appear equally often go in the order of their first appearance in text.
2. Hand the letters out from the queue to positions 0, 2, 4, …, and once the even positions run out, to positions 1, 3, 5, ….
Return the resulting string. Think about when no arrangement exists, and why in every other case this layout never puts two equal letters side by side.text="moon" → 'omon'
The queue is o, o (the most frequent), then m and n in order of first appearance. Positions 0 and 2 get the os, positions 1 and 3 get m and n: omon.
text="zzzy" → ''
Three zs cannot fit into four places without two of them touching, so the answer is the empty string.
text="banana" → 'ananab'
The queue is a, a, a, n, n, b: a has three copies, n two, b one. The even positions get the three as and the odd ones get n, n, b: ananab.
text consists of lowercase English letterstext="moon"
'omon'
Run checks the first 3 tests in your browser. Submit checks all 59 tests on the server, hidden ones included.