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.
We use a hash table or array \(\textit{cnt}\) to count the occurrences of each character in the string. Then, we use a max heap \(\textit{pq}\) to store each character and its count. Each element in the heap is a tuple \((v, c)\), where \(v\) is the count and \(c\) is the character.
When rearranging the string, we repeatedly pop the top element \((v, c)\) from the heap, add character \(c\) to the result string, and push \((v-1, c)\) into a queue \(\textit{q}\). When the length of the queue \(\textit{q}\) reaches \(k\) or more, we pop the front element; if its \(v\) is greater than \(0\), we push it back into the heap. Repeat this process until the heap is empty.
Finally, we check whether the length of the result string equals the original string. If so, we return the result string; otherwise, we return an empty string.
The time complexity is \(O(n \log n)\), where \(n\) is the length of the string. The space complexity is \(O(|\Sigma|)\), where \(|\Sigma|\) is the size of the character set, which is \(26\) in this problem.