Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
O(N) solution, generalization of rearrange string.

Pete Stenger

Oct 27, 2024

from heapq import * from collections import deque, Counter class Solution:   def reorganizeString(self, str, k):     counts = Counter(str)     heap = [       (-value, char) for char, value in counts.items()     ]     heapify(heap)     if -heap[0][0] > (len(str) + k - 1)//k:       return ''         res = list('_' * len(str))     i = 0     offset = 0     while heap:       count, char = heappop(heap)       while count < 0:         res[i] = char         i += k         if i >= len(res):           offset += 1           i = offset         count += 1     return ''.join(res)

0

0

Comments
Comments

On this page