Heaps Simulating with a heap
418. Reorganize String
You are given a string s. Rearrange its letters so that no two neighbouring characters are the same, and
return the new string. It must use every letter of s exactly as many times as s does.
Sometimes no such string exists. Then return the empty string "". Answers are shown in double quotes.
Many strings can be right, and any of them is a correct answer. The result shows a valid arrangement when
yours is one, and correctly impossible when you return "" and no arrangement exists. Otherwise it names
the first thing wrong, such as positions 4 and 5 are both 'a' or the letters changed: one 'b' is missing.
Positions count from 0.
Example 1
Input: s = "aaabbc"
"ababac"Explanation: No two neighbours are the same, and the string still has three a, two b and one c. "abacab" and
"acabab" are also correct.
Example 2
Input: s = "aab"
"aba"Explanation: a appears twice in three letters, so it has to take the first and the last position, with b between
them.
Example 3
Input: s = "zzzy"
""Explanation: Three z need two other letters to keep them apart, and there is only one y. Every order puts two z
side by side, so the answer is the empty string.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ s.length ≤ 105sholds only the lowercase lettersatoz.
Clarifying questions
What you would ask an interviewer before writing any code.