Faaez Razeen

Reorganize String

  • 2 min read
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O()O()
def reorganizeString(self, s: str) -> str: q = [(-freq, char) for char, freq in Counter(s).items()] heapify(q) new_s = [] while q: freq, char = heappop(q) if not new_s or new_s[-1] != char: new_s.append(char) if freq + 1: heappush(q, (freq + 1, char)) else: if not q: return '' next_freq, next_char = heappop(q) new_s.append(next_char) if next_freq + 1: heappush(q, (next_freq + 1, next_char)) heappush(q, (freq, char)) return ''.join(new_s)