mediumHeapGreedyHeap / Priority Queue

Reorganize String

mediumTime: O(n log k)Space: O(k)

Recognize the pattern

rearrange string so no two adjacent characters are the samemost frequent character dominatesgreedy placement

Brute force idea

The naive version of Reorganize String sounds like this: Try all permutations. Factorial. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The deeper shift in Reorganize String is this: Max-heap of (frequency, character). Always place the most frequent character that isn't the same as the last placed. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Reorganize String is one steady idea: If the most frequent character appears more than (n+1)/2 times, rearrangement is impossible. Otherwise, alternating the two most frequent characters always works. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

One easy way to drift off course in Reorganize String is this: Not checking feasibility first — if any character has frequency > (n+1)/2, return empty string immediately. The fix is usually to return to the meaning of each move, not just the steps themselves.

Heap / Priority Queue Pattern