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 INPUT String s = "aab" 'a' 'a' 'b' 0 1 2 Character Count: 'a': 2 'b': 1 Max freq (2) <= (3+1)/2 = 2 Possible: OK ALGORITHM STEPS 1 Count Frequencies Build freq map: a=2, b=1 2 Use Max Heap Priority: highest freq first Max Heap (2,'a') (1,'b') 3 Greedy Placement Pop max, place, hold prev 4 Push Back Prev Re-insert if freq > 0 Pop 'a'-->result, Pop 'b'-->result Push 'a' back, Pop 'a'-->result "a" --> "ab" --> "aba" FINAL RESULT Reorganized String: 'a' 'b' 'a' 0 1 2 Output: "aba" Verification: s[0]='a' != s[1]='b' : OK s[1]='b' != s[2]='a' : OK Valid: OK Key Insight: Use a Max Heap to always place the most frequent character next, while keeping track of the previous character. This greedy approach ensures no two adjacent characters are the same. Time: O(n log k) where k = unique chars | Space: O(k) for heap and frequency map TutorialsPoint - Reorganize String | Optimal Solution (Max Heap Greedy)
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