Problem · String
Reorganize a String
Learn this problemProblem statement
Rearrange a lowercase string so that no two adjacent characters are equal. If no such arrangement exists, return the empty string.
To make the judged result deterministic, construct the answer with this rule: at each position, select the eligible character with the greatest remaining frequency. The previously placed character is not eligible. If several eligible characters have the same frequency, select the lexicographically smallest one.
Function
reorganizeString(s: String) → StringExamples
Example 1
s = "aab"return = "aba"The highest-frequency eligible character is chosen first, producing a valid arrangement.
Example 2
s = "aaab"return = ""Three copies of one character cannot be separated by the single remaining character.
Example 3
s = "aabbcc"return = "abcabc"Frequency ties are resolved in lexicographic order while the previous character remains temporarily ineligible.
Constraints
1 <= s.length <= 10^5scontains only lowercase English letters.