sagelearnai

Reorganize String

Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #767

Rearrange the characters of s so that no two adjacent characters are the same. Return any valid arrangement, or "" if none exists. The tests check that your answer is a valid rearrangement.

Examples

text
"aab"  →  "aba"
"aaab" →  ""

Hints

  1. When is it impossible? Count the most frequent character.
  2. Each step, place the most frequent remaining character that differs from the previous one. That's a max-heap.
  3. Or skip the heap: fill indices 0, 2, 4, … first, starting with the most frequent letter.

Approach

Feasibility: a letter that appears more than ⌈n/2⌉ = (n+1)//2 times must end up next to itself somewhere. That's the only obstacle.

Even-index fill (O(n)): sort the letters by frequency, most frequent first, and write them into positions 0, 2, 4, …, wrapping to 1, 3, 5, … when you run out of even slots. The most frequent letter fits entirely on the even slots because its count is at most (n+1)//2. Every other letter has count ≤ n/2, so its copies are never adjacent: consecutive copies land two slots apart, and the wrap from the end of the evens to 1 puts them far apart.

Heap alternative: repeatedly pop the top two letters from a max-heap, append both, decrement them, and push them back. This is O(n log σ) and generalizes to "at least k apart" (LeetCode 358).

Complexity

Time: O(n + σ log σ). Space: O(n).

Python solution
from collections import Counter

def reorganizeString(s):
    n = len(s)
    cnt = Counter(s)
    if max(cnt.values()) > (n + 1) // 2:
        return ""
    res = [''] * n
    i = 0
    for ch, c in sorted(cnt.items(), key=lambda kv: -kv[1]):
        for _ in range(c):
            if i >= n:
                i = 1
            res[i] = ch
            i += 2
    return ''.join(res)
JavaScript solution
function reorganizeString(s) {
  const n = s.length, cnt = new Map();
  for (const ch of s) cnt.set(ch, (cnt.get(ch) || 0) + 1);
  if (Math.max(...cnt.values()) > (n + 1) >> 1) return '';
  const res = new Array(n);
  let i = 0;
  for (const [ch, c] of [...cnt].sort((a, b) => b[1] - a[1])) {
    for (let k = 0; k < c; k++) {
      if (i >= n) i = 1;
      res[i] = ch;
      i += 2;
    }
  }
  return res.join('');
}