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 of lowercase letters, rearrange its characters so that no two neighbouring characters are the same. Return any arrangement that works, or the empty string "" if there is none.

Example 1
Input: s = "aab"
Output: "aba"
Example 2
Input: s = "aaab"
Output: ""
Explanation: three a's need at least two other letters between them, and there is only one b.
Solution

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" becomes "aba", with the b between the two a's.

Example 2, "aaab", has three a's. Three a's leave two gaps between them, and each gap needs a letter that is not an a. There is only one b, so one gap stays empty and two a's end up side by side. Whether it can be done depends on the letter with the most copies.

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": three a's, two b's and one c. Writing from left to right, if we used the rare letters first, say "bcb", the three a's would be left for the end with nothing to separate them. The letters with the most copies are the hard ones to place, so they should go first, while other letters are still there to sit between them.

So each round, write the two letters with the most copies left, the one with more copies first. Look at the picture below.

Reorganizing aaabbc. Round 1: copies left a:3, b:2, c:1, and ab is written. Round 2: a:2, b:1, c:1, and ab is written. Round 3: a:1, c:1, and ac is written. The result so far ends as ababac.

Under "copies left", a:3 means three a's are still to be written. In round 1, the two orange boxes, a and b, have the most copies, so "ab" is written. In round 2, b and c both have one copy left, and b is taken because it comes first in the alphabet. In round 3 only a and c are left, and "ac" completes the result, "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", n is 4 and the limit is (4 + 1) / 2 = 2 in Java's whole-number division, but a has 3 copies.

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 PriorityQueue, in java.util. By default its top item is the smallest, which makes it a min-heap.

Here each item is a small array {letter, copies left}, with the letter stored as 0 for a up to 25 for z. A comparator, a function that decides which of two items comes first, turns the queue into a max-heap by copies left:

Java
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 works in these steps:

  1. First, count each letter in an array count of 26 numbers, where count[0] is the number of a's and count[25] the number of z's.
  2. Create heap, a PriorityQueue of {letter, copies left} arrays with the max-heap comparator, and compute limit as (s.length() + 1) / 2. A loop over the 26 letters returns "" as soon as a count is over limit, and adds every letter that appears to heap.
  3. Build the answer in a StringBuilder named sb. While heap holds at least two letters, take out first and second, append both, lower each one's copies by one, and put each back only if it has copies left.
  4. After that loop, if one letter is still in heap, append it once, then return sb as a string.

The main method runs both examples, "aaabbc" from the picture, "aaabb" and "aaaabb", which sit exactly at and just over the limit, "aabb" with tied counts, and a single letter.

Java
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:

Output
"aab" -> "aba"
"aaab" -> ""
"aaabbc" -> "ababac"
"aaabb" -> "ababa"
"aaaabb" -> ""
"aabb" -> "abab"
"z" -> "z"

The line for "aaabbc" shows "ababac", the same result the picture builds in three rounds. The next two lines show where the limit sits. "aaabb" has three a's in five places, exactly (5 + 1) / 2, and becomes "ababa", with an a in every other place. "aaaabb" has four a's against a limit of 3, so it returns "".

That limit must round up for odd lengths, which is why the code adds 1 before dividing. With s.length() / 2 instead, "aaabb" gets a limit of 2 and the method returns "", although "ababa" works. Example 1, "aab", fails in the same way.

In "aabb" the two letters tie in both rounds, and the alphabet tie-break puts a first each time, so the result is "abab". A single letter such as "z" never enters the loop and is added by the last step on its own.

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 s is.

Spacing out repeated items also drives Task Scheduler.