← Back to Algorithms, page 4

algorithms-0063 · Medium mid

Reorganize a string so that no two adjacent characters are the same, or report that it is impossible, using a greedy heap strategy.

It is impossible exactly when the most frequent character appears more than (n + 1) // 2 times. Otherwise, repeatedly take the most frequent character that differs from the one just placed, using a max-heap and holding the last-used character out for one step. That is O(n log A) time, where A is the alphabet size, and O(A) heap space.

Full answer

Problem

Given a string s, rearrange its characters so that no two adjacent characters are equal. Return any valid arrangement, or "" if none exists.

Example: "aab" becomes "aba"; "aaab" returns "".

Constraints: 1 <= len(s) <= 500, lowercase letters.

Brute force

Try permutations until one has no equal neighbours: O(n!) and only usable for tiny inputs (the tests use it as a reference for strings up to 7 characters).

Optimal approach

  1. Count characters. If the top count exceeds (n + 1) // 2, return "".
  2. Push (-count, char) for each character into a heap.
  3. Loop: pop the most frequent character, append it, then push back the character held from the previous step (if it still has copies). Hold the current one (with its count reduced) for the next step.

The held character cannot be chosen twice in a row because it is outside the heap during the next pick.

Why it works

Placing the most frequent available character first is the safe choice: the risk of failure comes from the character with the most copies left, and using it as often as allowed spreads it out. The counting bound is necessary because in n positions with no two neighbours equal, one character can fill at most every other slot, which is (n + 1) // 2 slots. When the bound holds, the greedy never gets stuck, which the random cross-check confirms against exhaustive search.

Complexity

O(n log A) time where A is the number of distinct characters (at most 26 here, so effectively O(n)). O(A) space for the heap and counts, plus the output.

Code

python
import heapq
import random
from collections import Counter
from itertools import permutations


def reorganize(s):
    """Rearrange so no two adjacent characters match, or return ''.
    Greedy with a max-heap: always place the most frequent character that differs from the last one."""
    counts = Counter(s)
    if counts and max(counts.values()) > (len(s) + 1) // 2:
        return ""                        # impossible: the top character cannot be separated
    heap = [(-c, ch) for ch, c in counts.items()]
    heapq.heapify(heap)
    out, held = [], None                 # held: the character used last step, waiting one turn
    while heap:
        c, ch = heapq.heappop(heap)
        out.append(ch)
        if held:
            heapq.heappush(heap, held)
        held = (c + 1, ch) if c + 1 < 0 else None
    return "".join(out)


def valid(s, t):
    return sorted(s) == sorted(t) and all(a != b for a, b in zip(t, t[1:]))


def brute_possible(s):
    return any(valid(s, "".join(p)) for p in set(permutations(s)))


if __name__ == "__main__":
    assert valid("aab", reorganize("aab"))
    assert reorganize("aaab") == ""
    assert reorganize("") == "" and reorganize("a") == "a"
    assert valid("aaabbc", reorganize("aaabbc"))
    rng = random.Random(63)
    for _ in range(600):
        s = "".join(rng.choice("aabbc") for _ in range(rng.randint(1, 7)))
        got = reorganize(s)
        assert (got != "") == brute_possible(s)
        if got:
            assert valid(s, got)
    print("all tests passed")

Save as b63_reorganize_string.py and run python3 b63_reorganize_string.py. It prints all tests passed (Python 3.13.5).

Edge cases

Single character string. All characters the same (only valid if length 1). Exactly (n + 1) // 2 copies of one character (valid, it fills every other slot). Empty string returns "".

Pattern

Greedy scheduling with a max-heap and a cooldown. The task scheduler problem (identical tasks must be k slots apart) uses the same loop with a queue of cooling items, and "distant barcodes" is the same problem on integers. An alternative O(n) method fills even indices first with the most frequent character, then the rest.

python
import heapq
import random
from collections import Counter
from itertools import permutations


def reorganize(s):
    """Rearrange so no two adjacent characters match, or return ''.
    Greedy with a max-heap: always place the most frequent character that differs from the last one."""
    counts = Counter(s)
    if counts and max(counts.values()) > (len(s) + 1) // 2:
        return ""                        # impossible: the top character cannot be separated
    heap = [(-c, ch) for ch, c in counts.items()]
    heapq.heapify(heap)
    out, held = [], None                 # held: the character used last step, waiting one turn
    while heap:
        c, ch = heapq.heappop(heap)
        out.append(ch)
        if held:
            heapq.heappush(heap, held)
        held = (c + 1, ch) if c + 1 < 0 else None
    return "".join(out)


def valid(s, t):
    return sorted(s) == sorted(t) and all(a != b for a, b in zip(t, t[1:]))


def brute_possible(s):
    return any(valid(s, "".join(p)) for p in set(permutations(s)))


if __name__ == "__main__":
    assert valid("aab", reorganize("aab"))
    assert reorganize("aaab") == ""
    assert reorganize("") == "" and reorganize("a") == "a"
    assert valid("aaabbc", reorganize("aaabbc"))
    rng = random.Random(63)
    for _ in range(600):
        s = "".join(rng.choice("aabbc") for _ in range(rng.randint(1, 7)))
        got = reorganize(s)
        assert (got != "") == brute_possible(s)
        if got:
            assert valid(s, got)
    print("all tests passed")

Feasibility bound, heap with a one-step hold, and an exhaustive permutation reference for short strings.

Complexity

Time: O(n log A). Space: O(A). With a fixed 26-letter alphabet this is effectively O(n); the even-index filling method is O(n) without a heap.

By level

Fresher: Derives the (n + 1) // 2 bound by thinking about every other slot. Follows the heap-based greedy step by step on a small input.

Mid: Implements the heap loop with the hold step and handles the impossible case. Extends it to the k-apart task scheduler with a cooldown queue.

Senior: Proves or argues why the greedy cannot get stuck when the bound holds, and presents the O(n) even-index filling method. Relates the pattern to rate-limited job scheduling and fair interleaving of tenants.

Key points

  • Impossible when max count > (n + 1) // 2
  • Always place the most frequent allowed character
  • Hold the last character out for one step
  • Heap of (-count, char)
  • Same skeleton as task scheduler

Common mistakes

  • Pushing the just-used character back immediately so it can repeat
  • Using the bound n // 2 instead of (n + 1) // 2
  • Forgetting characters whose count reaches zero
  • Not handling the impossible case before looping

Follow-ups

  • How does this change if equal characters must be at least k apart?
  • Can you solve it in O(n) without a heap?
  • How would you minimize idle slots in the task scheduler version?

Tips

  • State the feasibility bound first
  • Explain why the held character cannot repeat
  • Relate to the task scheduler

Evaluation rubric

  • Correct impossibility check
  • Valid output for possible inputs
  • Correct complexity
  • Explains the greedy choice