Rearrange characters in a string such that no two adjacent are same

Pattern: Top K

medium

Greedy with a max heap of letter counts: always place the most frequent letter allowed, and hold the letter just used out for one turn. If letters are left over that cannot be placed, it is impossible and the answer is the empty string.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Rearrange the letters of s (lowercase) so that no two neighbours are equal, and return any such arrangement, or "" when none exists. "aab" can give "aba"; "aaab" gives "". The tests accept any valid answer.

The catalogue has no practice link for this one; LeetCode's Reorganize String is the same problem.

Think first

  • When is it impossible?
  • Which letter is the most dangerous to leave for later?
  • How do you stop the same letter twice in a row?

Hints

    Brute force, and why it fails

    Try every permutation and check it: O(n!).

    The key insight

    Always place the most frequent letter that is allowed. A max heap gives it in O(log 26); holding the last-used letter out for one turn stops it repeating. The only way to get stuck is when one letter is too common.

    Dry run

    outa
    helda1

    s = "aab": counts a 2, b 1. Pop a, append it, hold a with 1 left.

    Step 1 of 4

    The plan

    heap = max heap of (count, letter)
    held = none
    while heap:
        (n, c) = pop; append c
        if held still has count: push held
        held = (n - 1, c)
    return result if its length is len(s) else ""
    

    Complexity

    Time
    O(n log 26) = O(n)
    Space
    O(26)

    Each placed letter costs a heap push and pop on at most 26 entries.

    Edge cases

    • One letter: itself.
    • All the same letter, more than one: impossible.
    • Exactly (n + 1) / 2 copies of one letter: just possible.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public String rearrangeString(String s) {
            int[] count = new int[26];
            for (char c : s.toCharArray()) count[c - 'a']++;
            PriorityQueue<int[]> heap = new PriorityQueue<>((x, y) -> y[1] - x[1]);   // {letter, count}, most left first
            for (int i = 0; i < 26; i++) if (count[i] > 0) heap.add(new int[]{i, count[i]});
            StringBuilder out = new StringBuilder();
            int[] held = null;                      // the letter just used must sit out one turn
            while (!heap.isEmpty()) {
                int[] top = heap.poll();
                out.append((char) ('a' + top[0]));
                top[1]--;
                if (held != null && held[1] > 0) heap.add(held);
                held = top;
            }
            return out.length() == s.length() ? out.toString() : "";   // stuck: some letter had no partner
        }
    }

    C++

    class Solution {
    public:
        string rearrangeString(string s) {
            int count[26] = {0};
            for (char c : s) count[c - 'a']++;
            priority_queue<pair<int, int>> heap;    // {count, letter}, most left first
            for (int i = 0; i < 26; i++) if (count[i] > 0) heap.push(make_pair(count[i], i));
            string out;
            pair<int, int> held(0, -1);             // the letter just used must sit out one turn
            while (!heap.empty()) {
                pair<int, int> top = heap.top();
                heap.pop();
                out += static_cast<char>('a' + top.second);
                top.first--;
                if (held.first > 0) heap.push(held);
                held = top;
            }
            return out.size() == s.size() ? out : "";   // stuck: some letter had no partner
        }
    };

    Python

    import heapq
    from collections import Counter
    
    class Solution:
        def rearrangeString(self, s: str) -> str:
            heap = [(-n, c) for c, n in Counter(s).items()]   # most left first
            heapq.heapify(heap)
            out, held = [], None                    # the letter just used must sit out one turn
            while heap:
                n, c = heapq.heappop(heap)
                out.append(c)
                if held and held[0] < 0:
                    heapq.heappush(heap, held)
                held = (n + 1, c)
            return "".join(out) if len(out) == len(s) else ""   # stuck: some letter had no partner

    Common mistakes

    • Putting the letter just used straight back, so it can be picked again.
    • Forgetting to check whether every letter was placed.

    Similar problems