Similar to the Task Scheduler, we use a Max-Heap to always pick the most frequent character. We keep track of the previously used character to avoid placing it again immediately.
- Count frequencies.
- Store
(-freq, char)in a Max-Heap. - Initialize
prev = None. - While heap is not empty:
- Pop character
c. - Append
cto result. - If
prevexists, push it back to the heap. - Decrement frequency of
c. If still > 0, setprev = (new_freq, c). Elseprev = None.
- Pop character
- If the resulting string length != input string length, return "".
- Time Complexity: O(N log K), where K is the alphabet size.
- Space Complexity: O(K).
import heapq
from collections import Counter
def reorganize_string(s):
counts = Counter(s)
max_heap = [(-f, c) for c, f in counts.items()]
heapq.heapify(max_heap)
prev = None
res = []
while max_heap or prev:
# If heap is empty but prev exists, it's impossible
if not max_heap and prev:
return ""
freq, char = heapq.heappop(max_heap)
res.append(char)
# After using prev, it's safe to put it back
if prev:
heapq.heappush(max_heap, prev)
prev = None
# Update current char and set as prev
if freq + 1 < 0:
prev = (freq + 1, char)
return "".join(res)