Algo-Sim › Heaps & Priority Queues

Reorganize String

Medium · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input

Greedy with a max-heap of letter counts: place the most common letter, and hold it back one round so it never repeats.

Problem

Rearrange the characters of string s so that no two adjacent characters are the same. Return any valid rearrangement, or the empty string "" if none exists.

Constraints

Edge cases to test

Follow-up questions

Is there a heap-free method?
Write the most common letter into even indices, then fill the rest of the even and then odd indices: O(n).
What if equal letters must be k apart?
Hold popped letters in a queue for k rounds before they return to the heap (LC 358).

Solution

Java

public String reorganizeString(String s) {
    int[] count = new int[26];
    for (char c : s.toCharArray()) count[c - 'a']++;
    // Most copies left first; equal counts go alphabetically.
    PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[1] != b[1] ? b[1] - a[1] : a[0] - b[0]);
    for (int c = 0; c < 26; c++) {
        if (count[c] > 0) heap.offer(new int[] {c, count[c]});
    }
    StringBuilder out = new StringBuilder();
    int[] held = null;
    while (!heap.isEmpty()) {
        int[] top = heap.poll();
        out.append((char) ('a' + top[0]));
        top[1]--;
        if (held != null) heap.offer(held);
        held = top[1] > 0 ? top : null;
    }
    return held == null ? out.toString() : "";
}

Python

import heapq
from collections import Counter


def reorganize_string(s):
    count = Counter(s)
    heap = []  # (-copies left, letter)
    for c in sorted(count):
        heapq.heappush(heap, (-count[c], c))
    out, held = [], None
    while heap:
        n, c = heapq.heappop(heap)
        out.append(c)
        n += 1  # one copy used (n is negative)
        if held:
            heapq.heappush(heap, held)
        held = (n, c) if n < 0 else None
    return "" if held else "".join(out)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    string reorganizeString(string &s) {
        vector<int> count(26);
        for (char c : s)
            count[c - 'a']++;
        // Most copies left first; equal counts go alphabetically.
        auto later = [](const pair<int, int> &a, const pair<int, int> &b) { return a.second != b.second ? a.second < b.second : a.first > b.first; };
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(later)> heap(later);
        for (int c = 0; c < 26; c++) {
            if (count[c] > 0)
                heap.push({c, count[c]});
        }
        string out;
        optional<pair<int, int>> held;
        while (!heap.empty()) {
            auto top = heap.top();
            heap.pop();
            out += char('a' + top.first);
            top.second--;
            if (held)
                heap.push(*held);
            held = top.second > 0 ? optional<pair<int, int>>(top) : nullopt;
        }
        return held ? "" : out;
    }
};

More Heaps & Priority Queues problems