Reorganize String - Problem
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code