Given a string s, reorder its characters so that no two adjacent characters are the same.
Return any valid rearrangement. If it is not possible to arrange the characters this way, return an empty string.
Example 1
Input: s = "aab"
Output: "aba"
Placing the two a's at positions 0 and 2 keeps them from touching.
Example 2
Input: s = "aaab"
Output: ""
Three a's cannot all be separated inside a four-character string, so no valid arrangement exists.
Constraints
1 <= s.length <= 500s consists of lowercase English letters.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI