The Rearrange String k Distance Apart problem asks you to rearrange a string so that the same characters are at least k positions apart. Return the rearranged string, or an empty string if it's impossible. This hard coding problem uses a greedy max-heap approach with a cooldown queue. The hash table, counting, sorting, heap, string, and greedy interview pattern is fully tested.
Amazon, TikTok, and Google ask this because it's the canonical greedy task-scheduling problem applied to strings. The solution demonstrates heap-based greedy with a cooldown window — directly modeling CPU scheduling with cooling periods.
Max-heap + cooldown queue. Use a max-heap of (frequency, character). A deque (cooldown queue) holds characters that must wait k steps before being reused. At each step: pop the highest-frequency character from heap, append to result, decrement its frequency, add to cooldown queue with a "release time" (current_step + k). When the front of the deque has reached its release time, push it back to the heap.
s="aaabc", k=2. Frequencies: {a:3,b:1,c:1}. Heap: [(3,a),(1,b),(1,c)].
Rearrange String k Distance Apart is the string variant of the Task Scheduler problem. The cooldown deque pattern is universal: place processed items in a "waiting zone" for exactly k steps, then release back to the main heap. Practice both problems together. If the result length < original string length, the arrangement is impossible — return "".
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Replace Question Marks in String to Minimize Its Value | Medium | Solve | |
| Reorganize String | Medium | Solve | |
| Minimum Deletions to Make String K-Special | Medium | Solve | |
| Minimum Number of Keypresses | Medium | Solve | |
| Minimum Number of Pushes to Type Word II | Medium | Solve |