Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Example 2:
Input: S = "aaab"
Output: ""
Note:
S will consist of lowercase letters and have length in range [1, 500].
Intuition
One consequence of the reasoning in Approach #1, is that a greedy approach that tries to write the most common letter (that isn’t the same as the previous letter written) will work.
The reason is that the task is only impossible if the frequency of a letter exceeds (N+1) / 2. Writing the most common letter followed by the second most common letter keeps this invariant.
A heap is a natural structure to repeatedly return the current top 2 letters with the largest remaining counts.
Approach
We store a heap of (count, letter). [In Python, our implementation stores negative counts.]
We pop the top two elements from the heap (representing different letters with positive remaining count), and then write the most frequent one that isn’t the same as the most recent one written. After, we push the correct counts back onto the heap.
At the end, we might have one element still on the heap, which must have a count of one. If we do, we’ll add that to the answer too.
class Solution {
public String reorganizeString(String S) {
int N = S.length();
int[] count = new int[26];
for (char c: S.toCharArray()) count[c-'a']++;
PriorityQueue<MultiChar> pq = new PriorityQueue<MultiChar>((a, b) ->
a.count == b.count ? a.letter - b.letter : b.count - a.count);
for (int i = 0; i < 26; ++i) if (count[i] > 0) {
if (count[i] > (N + 1) / 2) return "";
pq.add(new MultiChar(count[i], (char) ('a' + i)));
}
StringBuilder ans = new StringBuilder();
while (pq.size() >= 2) {
MultiChar mc1 = pq.poll();
MultiChar mc2 = pq.poll();
if (ans.length() == 0 || mc1.letter != ans.charAt(ans.length() - 1)) {
ans.append(mc1.letter);
ans.append(mc2.letter);
if (--mc1.count > 0) pq.add(mc1);
if (--mc2.count > 0) pq.add(mc2);
}
}
if (pq.size() > 0) ans.append(pq.poll().letter);
return ans.toString();
}
}
class MultiChar {
int count;
char letter;
MultiChar(int ct, char ch) {
count = ct;
letter = ch;
}
}