Reorganize String

Medium

Topics
Hash TableStringGreedySortingCounting

Rearrange the characters of s so that no two adjacent characters are the same.

If no such rearrangement exists, return the empty string. If several exist, return the lexicographically smallest one, so every input has exactly one correct answer.

Example 1

countsa ×2b ×1
answeraba
the most frequent letter
The chips give how often each letter occurs, which is all that decides whether an answer exists: the arrangement only has to avoid equal neighbours, so the one thing that can block it is a single letter being too common to keep apart. Here a fills 2 of 3 positions, at most the 2 a string this long can hold without a clash, so the answer row exists with its copies shaded and separated.
Only adjacency matters; the letters may appear in any order otherwise.
Input:  s = "aab"
Output: "aba"
Explanation: The only arrangement that separates the two as.

Example 2

countsa ×3b ×1
answer
empty string
the most frequent letter
Here a fills 3 of 4 positions when only 2 can be kept apart, so two copies must end up adjacent whatever the arrangement and the answer is the empty string.
Input:  s = "aaab"
Output: ""
Explanation: Three as and one other character: whatever the order, two as end up adjacent.

Example 3

countsv ×3l ×1o ×1
answervlvov
the most frequent letter
Input:  s = "vvvlo"
Output: "vlvov"
Explanation: Starting with l or o leaves three vs among four remaining positions, which cannot be separated — so the answer starts with v despite v being the larger letter.

Constraints

  • 1 <= s.length <= 500
  • s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls

Intuition

First, when is it impossible at all? The most frequent character has to be separated by the others, so with n characters in total and m copies of the commonest one, the copies need m - 1 separators and there are only n - m characters available. That gives the condition m <= (n + 1) / 2 rounded down — example 2 fails it with three as among four characters.

Second, which arrangement? Example 3 is the instructive one. Lexicographic order wants the smallest letter first, and l is smaller than v — but committing to l leaves three vs in four slots, which the condition above rules out. So the smallest answer is not simply the greedy alphabetical choice; each candidate has to be checked against whether the remainder is still arrangeable.

That makes the shape of the solution a left-to-right construction where each position tries its candidates in alphabetical order and accepts the first one that leaves a solvable remainder. Written as a search it is obviously correct and needs no feasibility argument at all; written with the counting condition above as the test it is fast, and the condition has to account for the character just placed, which is where subtle errors live.

Approach

  1. Count the characters. If the commonest appears more than (n + 1) / 2 times, return the empty string.
  2. Build the answer one position at a time, keeping the remaining counts and the character just placed.
  3. At each position, try the remaining characters in alphabetical order, skipping the one just placed. Take the first candidate from which the rest can still be completed.
  4. A search that recurses and backtracks on failure is exact; the counting condition from the intuition can replace the recursion once you trust it.

Walkthrough

s = "vvvlo"      counts v:3 l:1 o:1,  n = 5

impossible? m = 3 and (5 + 1) / 2 = 3, so 3 <= 3 -- possible

position 0, candidates in alphabetical order
   l  -> remaining v:3 o:1, four slots, commonest 3 > (4+1)/2 = 2
         not completable, reject
   o  -> same shape, reject
   v  -> remaining v:2 l:1 o:1, accept

position 1, cannot repeat v
   l  -> remaining v:2 o:1, accept

position 2, cannot repeat l
   o  -> remaining v:2, two slots, both v, adjacent -- reject
   v  -> accept

position 3, cannot repeat v
   o  -> accept,  position 4 takes the last v

answer vlvov

Complexity

  • Time — O(n * 26): each position tries at most 26 candidates, and the completability test is a scan of 26 counts. Without the test the search can backtrack, which the test prevents.
  • Space — O(n): the 26 counts are O(1) and the answer is O(n). Worth separating out the part that is easy to miss: build recurses once per placed character, so the call stack is itself n frames deep. It does not change the O(n) total, but on a 10^5-character input that is 10^5 stack frames, which is where a recursive solution in Python hits the default limit and an iterative loop would not.

Common Pitfalls

  • Taking the alphabetically smallest available character that differs from the previous one, without checking the remainder. Example 3 is exactly this trap.
  • Getting the impossibility bound wrong. It is (n + 1) / 2 rounded down, not n / 2 — "aab" has two as in three characters and is fine.
  • Forgetting that the completability test depends on which character was just placed. Two copies left in two slots is fine in general and not fine if they are both the character just used.
  • Returning any valid arrangement. Most published solutions do, and this statement asks for one specific one.

Full Solution — all languages

class Solution:
    def reorganizeString(self, s):
        counts = {}
        for c in s:
            counts[c] = counts.get(c, 0) + 1
        letters = sorted(counts)
        n = len(s)
        out = []
        dead = set()

        def key(prev):
            return prev + "|" + ",".join(str(counts[c]) for c in letters)

        def build(prev):
            if len(out) == n:
                return True
            k = key(prev)
            if k in dead:
                return False
            for c in letters:
                if counts[c] == 0 or c == prev:
                    continue
                counts[c] -= 1
                out.append(c)
                if build(c):
                    return True
                out.pop()
                counts[c] += 1
            dead.add(k)
            return False

        return "".join(out) if build("") else ""
SensAI
Beta
Tap the mic to stop voice mode