Greedy Algorithms - Reorganize String (No Two Adjacent Same)
Consider the following buggy code for reorganizing a string. Which line contains the subtle bug that can cause the function to return an invalid string with adjacent identical characters?
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)
# Bug: missing check for impossible case
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
