Rearrange String k Distance Apart - Problem
You're given a string s and an integer k. Your task is to rearrange the characters in the string such that no two identical characters are closer than k positions apart.
This is like organizing a seating arrangement where certain people need to be separated by at least k seats! If it's impossible to create such an arrangement, return an empty string "".
Key Challenge: You need to strategically place the most frequent characters first while ensuring they maintain the required distance.
Example: For string "aabbcc" with k=3, one valid arrangement could be "abcabc" - notice how each 'a' is 3 positions apart, same for 'b' and 'c'.
Input & Output
example_1.py โ Basic case with k=3
$
Input:
s = "aabbcc", k = 3
โบ
Output:
"abcabc"
๐ก Note:
Each character appears twice, and with k=3, we need at least 3 positions between same characters. The arrangement 'abcabc' satisfies this: 'a' appears at positions 0 and 3 (distance = 3), 'b' at 1 and 4 (distance = 3), 'c' at 2 and 5 (distance = 3).
example_2.py โ Impossible case
$
Input:
s = "aaadbbcc", k = 2
โบ
Output:
""
๐ก Note:
Character 'a' appears 3 times, but with k=2 and string length 8, we can only place 'a' at most at positions 0, 2, 4, 6 - that's 4 possible positions for 3 occurrences. However, the arrangement is still impossible due to the distribution of other characters.
example_3.py โ Edge case k=0
$
Input:
s = "aaab", k = 0
โบ
Output:
"aaab"
๐ก Note:
When k=0 or k=1, no rearrangement constraints apply, so we can return the original string or any permutation. The original string itself is valid.
Constraints
- 1 โค s.length โค 105
- 0 โค k โค s.length
- s consists of lowercase English letters only
- If multiple valid arrangements exist, return any one of them
Visualization
Tap to expand
Understanding the Visualization
1
Count VIP Guests
Count how many of each VIP type we need to seat (character frequencies)
2
Priority Seating
Always seat the most numerous VIP group first (max heap by frequency)
3
Cooldown Period
After seating a VIP, they enter a cooldown - can't be seated again for k positions
4
Cycle Management
As cooldown expires, VIPs become available for seating again
Key Takeaway
๐ฏ Key Insight: By prioritizing the most frequent characters (largest VIP groups) and using a systematic cooldown mechanism, we maximize our chances of successful arrangement while maintaining required distances.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code