You are given a string s and an integer k. Reorder the characters of s so that any two identical characters are separated by a distance of at least k positions.
If no such arrangement is possible, return an empty string. When k is 0 or 1 there is no spacing requirement, so the original string is already valid.
Example 1
Input: s = "aabbcc", k = 3
Output: "abcabc"
Each pair of identical letters ends up three positions apart, satisfying the distance requirement.
Example 2
Input: s = "aaabc", k = 3
Output: ""
There are three a's but only five slots, so at least two a's must land closer than three apart. It is impossible, so the answer is the empty string.
Constraints
1 <= s.length <= 3 * 10^5s consists of only lowercase English letters.0 <= k <= s.lengthSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI