Greedy Algorithms - Reorganize String (No Two Adjacent Same)
Given the following Python code implementing the max heap approach to reorganize a string, what is the output when the input is
"aab"?
import heapq
from collections import Counter
def reorganizeString(s: str) -> str:
freq = Counter(s)
max_heap = [(-count, ch) for ch, count in freq.items()]
heapq.heapify(max_heap)
prev_count, prev_char = 0, ''
result = []
while max_heap:
count, ch = heapq.heappop(max_heap)
result.append(ch)
if prev_count < 0:
heapq.heappush(max_heap, (prev_count, prev_char))
prev_count, prev_char = count + 1, ch
res_str = ''.join(result)
if len(res_str) != len(s):
return ""
return res_str
print(reorganizeString("aab"))