Problem
Rearrange the characters of a string so that no two adjacent characters are the same. Return any valid rearrangement, or an empty string if it is impossible.
Original: LeetCode 767: Reorganize String.
Examples
Example 1
`s = "aab"``"aba"`Example 2
`s = "aaab"``""`Three a's cannot be separated by one b.
Constraints
1 <= s.length <= 500sconsists of lowercase English letters.
Hints
Hint 1
The only obstruction is a character that is too frequent to be isolated. Any valid interleaving is accepted.
Hint 2
"Place the most frequent item, but not next to itself" is a max-heap of counts with a one-step delay of the last used item.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Generate permutations and test adjacency. That is factorial and not usable.
Optimal. A max-heap of remaining counts. Pop the best character, append it, then push the previously held character back. If the heap is empty before the string is finished, it is impossible. You can also prove impossibility first: a character may appear at most (n+1)/2 times.
Alternative. Place the most frequent character in even indices first, then fill the remaining indices, which is O(n) after counting.
Complexity
- Time
- O(n log A)
O(n log A) time, where A is the alphabet size, and O(A) extra space besides the output. For lowercase English letters A is 26.
- Space
- O(A)
Code
import heapq
from collections import Counter
def reorganize_string(s: str) -> str:
heap = [(-c, ch) for ch, c in Counter(s).items()]
heapq.heapify(heap)
out: list[str] = []
prev: tuple[int, str] | None = None
while heap:
count, ch = heapq.heappop(heap)
out.append(ch)
if prev and prev[0] < 0:
heapq.heappush(heap, prev)
prev = (count + 1, ch)
ans = "".join(out)
return ans if len(ans) == len(s) else ""
if __name__ == "__main__":
a = reorganize_string("aab")
assert len(a) == 3 and a[0] != a[1] and a[1] != a[2] and Counter(a) == Counter("aab")
assert reorganize_string("aaab") == ""
print("ok")import java.util.PriorityQueue;
public class ReorganizeString {
static String reorganizeString(String s) {
int[] freq = new int[26];
for (int i = 0; i < s.length(); i++) freq[s.charAt(i) - 'a']++;
var heap = new PriorityQueue<int[]>((a, b) -> Integer.compare(b[0], a[0]));
for (int c = 0; c < 26; c++) if (freq[c] > 0) heap.offer(new int[] {freq[c], c});
var out = new StringBuilder();
int[] prev = null;
while (!heap.isEmpty()) {
int[] cur = heap.poll();
out.append((char) ('a' + cur[1]));
cur[0]--;
if (prev != null && prev[0] > 0) heap.offer(prev);
prev = cur;
}
if (out.length() != s.length()) return "";
return out.toString();
}
static boolean ok(String s, String original) {
if (s.length() != original.length()) return false;
int[] a = new int[26], b = new int[26];
for (int i = 0; i < s.length(); i++) {
a[s.charAt(i) - 'a']++;
if (i > 0 && s.charAt(i) == s.charAt(i - 1)) return false;
}
for (int i = 0; i < original.length(); i++) b[original.charAt(i) - 'a']++;
for (int i = 0; i < 26; i++) if (a[i] != b[i]) return false;
return true;
}
public static void main(String[] args) {
String a = reorganizeString("aab");
if (!ok(a, "aab")) throw new AssertionError(a);
if (!reorganizeString("aaab").isEmpty()) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "aab" can be rearranged, for example as "aba"; "aaab" is impossible and returns an empty string.
- A single character, or all distinct characters, is already valid.
Follow-ups
- Reorganize String with a distance k, or Task Scheduler, generalizes the same cool-down idea.
Interview script
"If one character appears more than (n+1)/2 times, it is impossible. Otherwise I always append the current most frequent character that is not the one I just used, by holding the previous count out of the heap for one turn."
Source: LeetCode 767: Reorganize String Source: Java SE 17 API: PriorityQueue
Sources (2)
- LeetCode 767: Reorganize Stringleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com