LeetCode #767 Medium

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.

Constraints
  • 1 <= s.length <= 500
  • s consists of lowercase English letters.
heapgreedycountingstring
Open on LeetCode ↗
02

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.
How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1from collections import Counter
▶2 
▶3class Solution:
▶4 def reorganizeString(self, s):
▶5 n = len(s)
▶6 count = Counter(s)
▶7 top = max(count, key=count.get)
▶8 if count[top] > (n + 1) // 2:
▶9 return ""
▶10 result = [""] * n
▶11 i = 0
▶12 for ch in [top] + [c for c in count if c != top]:
▶13 for _ in range(count[ch]):
▶14 if i >= n:
▶15 i = 1
▶16 result[i] = ch
▶17 i += 2
▶18 return "".join(result)
letters leftv3 leftmostl1 lefto1 leftcheckresult01234count each letter; 'v' is the most common
countv: 3, l: 1, o: 1
slots5
Only the most common letter can make the task impossible, so find it first: 'v' appears 3 times. It will be placed first, then the other letters in any order.
letters leftv3 leftmostl1 lefto1 leftcheck3copies of v≤3even slotsresult0next12343 copies of 'v' fit in 3 even slots → build
copies3
limit3(n + 1) / 2
Slots 0, 2, 4, … are the even slots; a string of 5 has 3 of them, and no two are next to each other. 'v' fits in them, so an answer exists. Fill the even slots first, then the odd ones.
letters leftv2 leftmostl1 lefto1 leftcheck3copies of v≤3even slotsresultv012next34'v' → slot 0
result[0]'v'
left2copies of v
The most common letter takes every other slot from the front, so its copies always have a free slot between them.
letters leftv1 leftmostl1 lefto1 leftcheck3copies of v≤3even slotsresultv01v234next'v' → slot 2
result[2]'v'
left1copies of v
The most common letter takes every other slot from the front, so its copies always have a free slot between them.
letters leftv0 leftmostl1 lefto1 leftcheck3copies of v≤3even slotsresultv01v23v4'v' → slot 4
result[4]'v'
left0copies of v
The most common letter takes every other slot from the front, so its copies always have a free slot between them. The next even slot would be past the end.
letters leftv0 leftmostl1 lefto1 leftcheck3copies of v≤3even slotsresultv01nextv23v4past the end → start the odd slots at 1
i1first odd slot
Every even slot is full, so jump back to slot 1 and keep stepping by 2. 'l' has no copies placed yet, so it cannot land next to itself.
letters leftv0 leftmostl0 lefto1 leftcheck3copies of v≤3even slotsresultv0l1v23nextv4'l' → slot 1
result[1]'l'
left0copies of l
Each letter fills the next free slot two steps on, so its own copies are never next to each other. Its current neighbours are 'v' and 'v', both different.
letters leftv0 leftmostl0 lefto0 leftcheck3copies of v≤3even slotsresultv0l1v2o3v4'o' → slot 3
result[3]'o'
left0copies of o
Each letter fills the next free slot two steps on, so its own copies are never next to each other. Its current neighbours are 'v' and 'v', both different.
letters leftv0 leftmostl0 lefto0 leftcheck3copies of v≤3even slotsresultv0l1v2o3v4answer: "vlvov"
result"vlvov"
All 5 slots are filled and no two neighbours match. Other orders of the remaining letters give other valid answers, and any of them is accepted.
05

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.

06

Common pitfalls

Not placing the most common letter first

✗ Wrong
for ch in count:
    ...
✓ Right
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

✗ Wrong
if count[top] > n // 2:
    return ""
✓ Right
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

✗ Wrong
c, ch = heappop(heap)
result.append(ch)
heappush(heap, (c + 1, ch))
✓ Right
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".

07

Complexity

Time
O(n)
Space
O(n)
Counting is one pass and every slot is written once; the alphabet has only 26 letters, so finding the most common one is constant work. The result array holds n letters; besides it only the 26 counts are stored.
08

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.