Reorganize String

Rearrange so no two adjacent chars are equal — greedy max-heap by remaining count.

Medium
Time O(n log |Σ|) Space O(|Σ|)
LeetCode
6 min read
top-k heaps greedy

Problem#

Rearrange s so no two adjacent characters are equal. Return any valid rearrangement, or "" if impossible.

Examples#

  • "aab""aba"
  • "aaab"""

Constraints#

  • 1 <= s.length <= 500.

Hints#

Hint 1
Impossible iff some letter’s count exceeds (n+1)/2. Otherwise greedy works.

Approach#

Max-heap by count. Repeatedly pop the two most frequent, append one of each (so the just-used letter doesn’t reappear immediately), decrement, push back. The two-pop pattern guarantees no adjacency violation.

Solution#

Reorganize String
class Solution {
public:
string reorganizeString(string s) {
int cnt[26] = {0};
for (char c : s) ++cnt[c - 'a'];
int maxFreq = *max_element(cnt, cnt + 26);
if (maxFreq > (int)(s.size() + 1) / 2) return "";
priority_queue<pair<int,char>> pq;
for (int i = 0; i < 26; ++i) if (cnt[i]) pq.push({cnt[i], 'a' + i});
string out;
while (pq.size() >= 2) {
auto [c1, ch1] = pq.top(); pq.pop();
auto [c2, ch2] = pq.top(); pq.pop();
out += ch1;
out += ch2;
if (--c1) pq.push({c1, ch1});
if (--c2) pq.push({c2, ch2});
}
if (!pq.empty()) out += pq.top().second;
return out;
}
};

Editorial#

The feasibility check is exact: if any letter occurs more than ⌈n/2⌉ times, the pigeonhole guarantees an adjacency. Otherwise the two-pop greedy works: at each step we place two different letters, the most-frequent first, which strictly decreases the imbalance.

Complexity#

  • Time: O(n log |Σ|).
  • Space: O(|Σ|).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.