Reorganize String
Rearrange the letters of a string so that no two neighbours match, by writing the most common letters first.
Given a string s""
Example 1
Output: "aba"
Example 2
Output: ""
Explanation: three a's need at least two other letters between them, and there is only one b.
The Idea
Think of threading beads onto a cord, where two beads of the same colour must never touch. With two red beads and one blue bead it works: red, blue, red. Example 1 is the same puzzle with letters: "aab""aba"
Example 2, "aaab"
How many copies are too many? A letter can take at most every other place: places 1, 3, 5 and so on. A string of 5 characters has 3 such places, and so does a string of 6. For a string of length n that is (n + 1) / 2, rounded down. A letter with more copies than that makes the answer ""
When no letter is over that limit, in what order should the letters be written? Take "aaabbc""bcb"
So each round, write the two letters with the most copies left, the one with more copies first. Look at the picture below.
Under "copies left", a:3"ab""ac""ababac"
Each round takes the choice that looks best right now and never goes back to change it. Building an answer this way is called a greedy approach.
Solution Approach
Turning that idea into code means settling four things: when to give up, how to find the top two letters each round, why one round never clashes with the next, and what to do with a leftover letter.
When the answer is impossible
Which letter can make the answer impossible? Only one with more than (n + 1) / 2 copies. Counting the letters first, in an array of 26 counts, one for each letter from a to z, settles it before anything is written. For "aaab"
When every letter is within the limit, the rounds always finish without two equal letters touching.
Finding the letters with the most copies
Why not simply try every order of the letters and keep one that works? The number of orders explodes: 20 letters can be arranged in 20! ways, about 2.4 × 1018. Picking the top two letters each round is far less work.
A heap is a structure that keeps its items partly sorted, so that taking out the top item, or putting a new one in, takes about log k steps for k items. Java's heap class is PriorityQueuejava.util
Here each item is a small array {letter, copies left}
Comparator<int[]> byCopies = (x, y) -> x[1] != y[1] ? y[1] - x[1] : x[0] - y[0];
More copies come first, and on equal copies the letter earlier in the alphabet comes first. With only 26 letters, scanning all the counts every round would also work; the heap hands over the top letters directly and never holds more than 26 items.
The join between two rounds
The two letters inside a round are always different, but what about the last letter of one round and the first of the next? Call the two letters of a round P and Q, written in that order. P was taken first, so it had at least as many copies as Q, and then both lose one copy.
If P had more copies, it still has more. If they had the same number, the alphabet tie-break picked P first, and it still does. Either way, Q cannot start the next round. If P is used up, it had one copy, so Q had one copy too and is used up as well.
The letter left at the end
The rounds stop when fewer than two letters are left. What if exactly one is? It has a single copy, because the limit check rules out more. It is not Q, the letter written last: if Q were the one left, P would be used up, and then so is Q. So the leftover letter is added once at the end.
Java Solution
The method reorganizeString
- First, count each letter in an array
of 26 numbers, wherecount is the number of a's andcount[0] the number of z's.count[25] - Create
, aheap ofPriorityQueue arrays with the max-heap comparator, and compute{letter, copies left} aslimit . A loop over the 26 letters returns(s.length() + 1) / 2 as soon as a count is over"" , and adds every letter that appears tolimit .heap - Build the answer in a
namedStringBuilder . Whilesb holds at least two letters, take outheap andfirst , append both, lower each one's copies by one, and put each back only if it has copies left.second - After that loop, if one letter is still in
, append it once, then returnheap as a string.sb
The main"aaabbc""aaabb""aaaabb""aabb"
import java.util.PriorityQueue;
public class ReorganizeStringHeap {
public static String reorganizeString(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
// max-heap of {letter, copies left}: most copies first, ties by alphabet
PriorityQueue<int[]> heap = new PriorityQueue<>(
(x, y) -> x[1] != y[1] ? y[1] - x[1] : x[0] - y[0]);
int limit = (s.length() + 1) / 2;
for (int i = 0; i < 26; i++) {
if (count[i] > limit) {
return ""; // not enough other letters to separate it
}
if (count[i] > 0) {
heap.add(new int[] {i, count[i]});
}
}
StringBuilder sb = new StringBuilder();
while (heap.size() >= 2) {
int[] first = heap.poll(); // most copies left
int[] second = heap.poll(); // next most, a different letter
sb.append((char) ('a' + first[0])).append((char) ('a' + second[0]));
if (--first[1] > 0) {
heap.add(first);
}
if (--second[1] > 0) {
heap.add(second);
}
}
if (!heap.isEmpty()) {
sb.append((char) ('a' + heap.poll()[0])); // one letter, one copy left
}
return sb.toString();
}
public static void main(String[] args) {
String[] inputs = {"aab", "aaab", "aaabbc", "aaabb", "aaaabb", "aabb", "z"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + reorganizeString(s) + "\"");
}
}
}
Running it prints:
"aab" -> "aba"
"aaab" -> ""
"aaabbc" -> "ababac"
"aaabb" -> "ababa"
"aaaabb" -> ""
"aabb" -> "abab"
"z" -> "z"
The line for "aaabbc""ababac""aaabb""ababa""aaaabb"""
That limit must round up for odd lengths, which is why the code adds 1 before dividing. With s.length() / 2"aaabb""""ababa""aab"
In "aabb""abab""z"
Complexity
The work is one count of the letters, plus about n / 2 rounds that each take a few steps on a heap of at most 26 letters.
- Time: O(n), because counting reads each of the n letters once, and each round's two polls and two adds work on at most 26 items, so a round costs a fixed number of steps.
- Space: O(1) besides the answer, because the count array and the heap hold at most 26 entries however long
is.s
Spacing out repeated items also drives