Rearrange String k Distance Apart Problem
Description
LeetCode Problem 358.
Given a string s and an integer k, rearrange s such that the same characters are at least distance k from each other. If it is not possible to rearrange the string, return an empty string "".
Example 1:
Input: s = "aabbcc", k = 3
Output: "abcabc"
Explanation: The same letters are at least a distance of 3 from each other.
Example 2:
Input: s = "aaabc", k = 3
Output: ""
Explanation: It is not possible to rearrange the string.
Example 3:
Input: s = "aaadbbcc", k = 2
Output: "abacabcd"
Explanation: The same letters are at least a distance of 2 from each other.
Constraints:
1 <= s.length <= 3 * 10^5sconsists of only lowercase English letters.0 <= k <= s.length
Solution
Approach: Greedy with a Max-Heap and a Cooling Queue
Fill the result one position at a time. Among the letters we're allowed to use right now, take the one with the most occurrences left. A letter is allowed when it was not used in the last k - 1 positions. Using frequent letters early is what keeps the order valid. If we hold back a letter that has many copies left, we may end up with several of its copies at the end and no other letters to put between them.
To run this efficiently:
- A max-heap holds the letters that are allowed now, ordered by how many copies they have left.
- A queue holds the letters that were used recently, in the order we used them. Each one is "cooling down".
At each step, pop the top letter from the heap, add it to the result, lower its count, and push it onto the queue. Once the queue holds k letters, its oldest letter was used k positions ago, so it's allowed again: move it back to the heap if it still has copies left.
If the heap runs empty before the result is complete, every remaining letter is still cooling down and nothing can go in the next position. No valid order exists, so return "". You can spot this when the result ends up shorter than s. The edge cases k = 0 and k = 1 need no special handling: with them, a used letter goes back to the heap right away.
The JavaScript and Go versions skip the heap. There are only 26 letters, so they keep, for each letter, the first position where it may appear again, and at each position they scan the 26 letters for the allowed one with the most copies left. It's the same greedy choice.
Complexity: O(n log 26) = O(n) time with the heap (O(26n) with the scan). O(26) extra space besides the result.
from collections import Counter, deque
from heapq import heapify, heappop, heappush
class Solution:
def rearrangeString(self, s: str, k: int) -> str:
heap = [(-cnt, c) for c, cnt in Counter(s).items()] # max-heap on the remaining count
heapify(heap)
cooling = deque() # letters used in the last k positions, oldest first
ans = []
while heap:
cnt, c = heappop(heap)
ans.append(c)
cooling.append((cnt + 1, c)) # one fewer left (counts are negative)
if len(cooling) >= k:
# the oldest letter was placed k positions ago: it may be used again
cnt, c = cooling.popleft()
if cnt < 0:
heappush(heap, (cnt, c))
# the heap ran dry while letters were still cooling: no valid order exists
return "".join(ans) if len(ans) == len(s) else ""