Greedy Algorithms8 sections · 316 units
Open in Course

Reorganize String - Feasibility

When is it possible

A rearrangement is possible if and only if no character appears more than n/2\lceil n/2 \rceil times where nn is string length. Why? In the best case, you alternate the most frequent character with others.

If it appears more than half the time, you cannot avoid adjacent duplicates. For "aab" (length 33), max frequency is 3/2=2\lceil 3/2 \rceil = 2. Character 'a' appears twice, which is okay. For "aaab", 'a' appears 33 times but max allowed is 22. Impossible.