Skip to content
BytePatterns

Spread Letters at Least K Apart

MediumHeaps#max-heap#greedy#cooldown-queue~30m

Problem

Rearrange the letters of a string so that any two equal letters are at least k positions apart, meaning their indices differ by k or more. Among the letters allowed at each position, always place the one with the most copies left, taking the alphabetically smallest on a tie, so the answer is unique. If no arrangement exists, return an empty string. The string has up to 100,000 lowercase letters.

Examples

Input:  s = "aabbcc", k = 3
Output: "abcabc"
Why:    each letter waits for the other two before it can repeat
Input:  s = "aaadbbcc", k = 2
Output: "abacabcd"
Why:    a has the most copies, so it goes first whenever its cooldown allows
Input:  s = "aaabc", k = 3
Output: ""
Why:    edge case, three a's need a span of 7 positions and only 5 exist

Hints

0 / 3

Stuck on the idea rather than the code? Reorganize a String covers it.