Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of s or return "" (empty string) if not possible.

Input & Output

Example 1 — Basic Case
$ Input: s = "aab"
Output: "aba"
💡 Note: We can rearrange "aab" to "aba" where no two adjacent characters are the same. Another valid answer would be "baa".
Example 2 — Impossible Case
$ Input: s = "aaab"
Output: ""
💡 Note: We have 3 'a's and 1 'b'. Since 'a' appears more than (4+1)/2 = 2.5 times, it's impossible to arrange without adjacent duplicates.
Example 3 — Single Character
$ Input: s = "a"
Output: "a"
💡 Note: Single character strings are always valid since there are no adjacent pairs to worry about.

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists of lowercase English letters

Visualization

Tap to expand
Reorganize String: Transform "aab" → "aba"Input: "aab"aabAdjacent duplicates!Frequency Counta: 2b: 1Output: "aba"abaNo adjacent duplicates ✓Strategy: Alternate placement of most frequent charactersPlace 'a' at positions 0,2 then 'b' at position 1Key constraint: No character can appear more than ⌈n/2⌉ times
Understanding the Visualization
1
Input Analysis
Count character frequencies and check feasibility
2
Strategic Placement
Place characters to avoid adjacent duplicates
3
Valid Output
Return rearranged string or empty string if impossible
Key Takeaway
🎯 Key Insight: Use frequency counting and strategic placement - if any character appears more than ⌈n/2⌉ times, rearrangement is impossible
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
156.0K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen