classSolution:
defrearrangeString(self, s: str, k: int) -> str:
if k ==0:
return s
freq_map = Counter(s)
max_heap = [(-value, key) for key, value in freq_map.items()]
heapq.heapify(max_heap)
queue = deque()
result = []
while max_heap:
value, key = heapq.heappop(max_heap)
result.append(key)
queue.append((key, value +1))
if len(queue) >= k:
front = queue.popleft()
if front[1] <0:
heapq.heappush(max_heap, front)
return"".join(result) if len(result) == len(s) else""
⏰ Time complexity: O(n log n), where n is the length of the string. This is due to heap operations, which are O(log n), and we perform these operations n times.
🧺 Space complexity: O(n), due to the space used by the frequency map, the heap, and the queue.