Greedy Algorithms8 sections · 316 units
Open in Course

Reorganize String - Algorithm

Max-heap approach

Use a max-heap of (count, char). At each step, pop the most frequent character and add it to result. Then pop the second most frequent and add it. Push both back (with decremented counts) if they still have remaining occurrences. It ensures the most frequent characters are spread out. Time: O(n)O(n). Space: O(1)O(1). The two-pop pattern ensures you never pick the same character twice in a row.

If only one character remains in the heap and it has count >1> 1, it is impossible to place without adjacency. The heap maintains the greedy priority automatically.