Reorganize String
MediumP3Coding
Rearrange the characters of s so that no two adjacent characters are equal. Return the rearranged string, or "" if it is impossible.
Many arrangements can be valid, so build exactly this one: at every step place the letter that has the largest remaining count among the letters different from the one just placed, breaking ties by choosing the alphabetically smaller letter. If at some step no such letter is left, return "".
Example 1
- Input
- s = "aab"
- Output
- "aba"
Example 2
- Input
- s = "aaab"
- Output
- ""
- Why
- Three a's cannot be separated by a single b.
Example 3
- Input
- s = "vvvlo"
- Output
- "vlvov"
Constraints
- 1 <= s.length <= 500
- s consists of lower-case English letters
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 12. ⌘Enter runs, ⌘⇧Enter submits.