SDE & MLE Prep

767. Reorganize String

Problem

Rearrange the letters of s so that no two adjacent characters are equal, and return any such arrangement, or "" if it's impossible.

Example: "aab" → "aba"; "aaab" → ""

Constraints: length ≤ 500.

Greedy: always place the most frequent char that isn't the previous one. With a max-heap, pop the top, append it, then push back the previous char (held out for one turn). Impossible if any count > ⌈n/2⌉.

Complexity: O(n log 26).

class Solution:
    def reorganizeString(self, s: str) -> str:
        h = [(-c, ch) for ch, c in Counter(s).items()]
        heapify(h)
        res, prev = [], None
        while h:
            c, ch = heappop(h)
            res.append(ch)
            if prev:
                heappush(h, prev)
            prev = (c + 1, ch) if c + 1 < 0 else None
        return "".join(res) if not prev else ""