Reorganize String
Reorganize String is LeetCode 767 (Medium). Rearrange the letters of s so that no two adjacent characters are the same, and return any arrangement that works. If none exists, return "".
s holds 1 to 500 lowercase letters.
- 1 <= s.length <= 500
- s consists of lowercase English letters.
Intuition
Only the most common letter can make the task impossible. Its copies need a different letter between each pair, so a string of length n has room for at most (n + 1) / 2 of them: the even slots 0, 2, 4, …
- Check: if the most common letter appears more often than that, no arrangement exists.
- Build: otherwise put that letter in the even slots from the front, keep filling even slots with the other letters, and when they run out continue in the odd slots from 1. Writing every letter two slots apart keeps its copies from touching, and the most common letter going first guarantees it gets all the space it needs.
"Rearrange so no two equal items are adjacent" is decided by the most frequent item and a pigeonhole count. Task Scheduler and Distant Barcodes use the same bound; Distant Barcodes can be solved with this exact even-then-odd fill.
Approach
Before reading on, work out how many copies of one letter fit in a string of length 5 without two touching. Then decide which letter should be placed first, and where. Aim for O(n).
Two ways to solve it
Write the most common letter into slots 0, 2, 4, …, then the rest, wrapping to slot 1.
- Direct: every slot is written once.
- No heap: just the 26 counts.
- Proof: a short counting argument shows no letter meets itself.
Pop the two most common letters, append both, and push back any that still have copies.
- Greedy: always use what is most at risk of running out of room.
- Generalises: the same idea, with a waiting queue, handles a gap of
k. - k: distinct letters, at most 26.
Both rest on the same check that the most common letter fits in (n + 1) / 2 slots. The even-slot fill wins because it is O(n), needs no heap and has no rounds to get wrong. The steps, code and live demo follow it; the heap code comes after the demo.
Count and find the most common letter
Count every letter with Counter(s) and take the one with the highest count. It is the only letter that can run out of room, so the rest of the algorithm is built around it.
Reject it if it cannot fit
If its count is above (n + 1) // 2, return "" at once. Past this check an answer is guaranteed, so the building steps never need to fail.
Fill even slots, most common letter first
Start a write index at 0 and step it by 2. Write every copy of the most common letter first, then the other letters in any order. Stepping by 2 leaves a free slot between any two letters written one after the other.
Wrap to the odd slots
When the index passes the end, set it to 1 and keep stepping by 2. The even slots are full by then, so the odd slots fill the gaps between them from the front.
Why a wrapping letter never meets itself
Say a wrapping letter has a copies in the last even slots and b in the first odd slots, out of L even slots. It touches itself only if a + b ≥ L. But it has no more copies than the most common letter, which shares the even slots with these a, so a + b ≤ L − a < L.
Code in Python, C++ and Java
Max-heap, two letters per round
Keep (count, letter) pairs in a max-heap. Each round pops the two most common letters and appends both, so the two letters of a round always differ, and the second one separates the first from its next copy. A letter goes back into the heap only if copies remain. If one letter is left at the end with more than one copy, there was no answer; with exactly one copy it goes last.
Common pitfalls
Not placing the most common letter first
for ch in count:
...for ch in [top] + [c for c in count if c != top]:
...The proof that wrapping is safe only holds when the most common letter fills the front even slots. On "baa" the loop meets b first: b takes slot 0, then a takes slot 2, wraps to slot 1, and the result is "baa" with two as together.
Using n // 2 as the limit
if count[top] > n // 2:
return ""if count[top] > (n + 1) // 2:
return ""For odd n there is one more even slot than odd slot. "aab" has n = 3 and two as, which fit as "aba", but 3 // 2 = 1 rejects it.
Heap version: pushing a letter back right after using it
c, ch = heappop(heap) result.append(ch) heappush(heap, (c + 1, ch))
c1, a = heappop(heap) c2, b = heappop(heap) result += [a, b]
The letter just used is often still the most common one, so the next pop returns it again. On "aab" the first two pops both return a, giving "aa".
Complexity
Reorganize String FAQ
How is Reorganize String different from Task Scheduler?
Task Scheduler (LeetCode 621) also depends on the most frequent item, but it may leave a slot idle and asks only for the total length. Here every slot must hold a real letter and equal letters only need one letter between them. Rearrange String k Distance Apart (LeetCode 358) raises that gap to k, where even-and-odd slots no longer work and a heap with a waiting queue is used.