358. Rearrange String k Distance Apart
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Greedy with Max-Heap and Queue
This problem asks us to rearrange a string such that any two identical characters are at least k distance apart. This can be framed as a scheduling problem: at each position in the new string, we need to choose a character to place. The best strategy is a greedy one.
Solution
Rearrange String k Distance Apart in Python
from collections import Counter, deque
import heapq
class Solution:
def rearrangeString(self, s: str, k: int) -> str:
if k == 0:
return s
n = len(s)
result = []
# 1. Count character frequencies
counts = Counter(s)
# 2. Build a max-heap. heapq is a min-heap, so we store negative frequencies.
max_heap = [(-freq, char) for char, freq in counts.items()]
heapq.heapify(max_heap)
# 3. Use a deque as a wait queue for characters on cooldown
wait_queue = deque()
while len(result) < n:
# If the heap is empty, we are stuck, no valid character to place
if not max_heap:
return ""
# 4. Get the most frequent character
freq, char = heapq.heappop(max_heap)
# Append to result
result.append(char)
# Add to wait_queue with decremented count (still negative)
wait_queue.append((freq + 1, char))
# 5. If wait_queue has k elements, the one at the front is ready
if len(wait_queue) == k:
cooled_freq, cooled_char = wait_queue.popleft()
if cooled_freq < 0: # a count of -1 means original count was > 1
heapq.heappush(max_heap, (cooled_freq, cooled_char))
return "".join(result)
Rearrange String k Distance Apart in Java
class Solution {
public String rearrangeString(String s, int k) {
if (k == 0) {
return s;
}
int n = s.length();
// 1. Count character frequencies
Map<Character, Integer> counts = new HashMap<>();
for (char c : s.toCharArray()) {
counts.put(c, counts.getOrDefault(c, 0) + 1);
}
// 2. Build a max-heap (PriorityQueue) based on frequency
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
(a, b) -> b.getValue() - a.getValue()
);
pq.addAll(counts.entrySet());
// 3. Use a queue to keep track of characters on cooldown
Queue<Map.Entry<Character, Integer>> waitQueue = new LinkedList<>();
StringBuilder result = new StringBuilder();
while (result.length() < n) {
// If the heap is empty, it means we are stuck, no valid character to place
if (pq.isEmpty()) {
return "";
}
// 4. Get the most frequent character
Map.Entry<Character, Integer> entry = pq.poll();
// Append it to the result
result.append(entry.getKey());
// Decrement its count and add to the waitQueue
entry.setValue(entry.getValue() - 1);
waitQueue.offer(entry);
// 5. If the waitQueue has k elements, the one at the front is ready to be used again
if (waitQueue.size() == k) {
Map.Entry<Character, Integer> front = waitQueue.poll();
if (front.getValue() > 0) {
pq.offer(front);
}
}
}
return result.toString();
}
}
Rearrange String k Distance Apart in C++
class Solution {
public:
string rearrangeString(string s, int k) {
if (k == 0) {
return s;
}
int n = s.length();
string result = "";
// 1. Count character frequencies
unordered_map<char, int> counts;
for (char c : s) {
counts[c]++;
}
// 2. Build a max-heap (priority_queue) based on frequency
priority_queue<pair<int, char>> pq;
for (auto const& [key, val] : counts) {
pq.push({val, key});
}
// 3. Use a queue to keep track of characters on cooldown
queue<pair<int, char>> waitQueue;
while (result.length() < n) {
// If the heap is empty, it means we are stuck, no valid character to place
if (pq.empty()) {
return "";
}
// 4. Get the most frequent character
pair<int, char> top = pq.top();
pq.pop();
// Append it to the result
result += top.second;
// Decrement its count and add to the waitQueue
top.first--;
waitQueue.push(top);
// 5. If the waitQueue has k elements, the one at the front is ready to be used again
if (waitQueue.size() == k) {
pair<int, char> front = waitQueue.front();
waitQueue.pop();
if (front.first > 0) {
pq.push(front);
}
}
}
return result;
}
};
Rearrange String k Distance Apart in TypeScript
type FreqPair = [number, string]; // [frequency, character]
class PriorityQueue {
private heap: FreqPair[] = [];
constructor() {}
size(): number {
return this.heap.length;
}
isEmpty(): boolean {
return this.size() === 0;
}
push(val: FreqPair) {
this.heap.push(val);
this.siftUp(this.size() - 1);
}
pop(): FreqPair | undefined {
if (this.isEmpty()) return undefined;
this.swap(0, this.size() - 1);
const popped = this.heap.pop();
this.siftDown(0);
return popped;
}
private parent(i: number): number {
return Math.floor((i - 1) / 2);
}
private leftChild(i: number): number {
return 2 * i + 1;
}
private rightChild(i: number): number {
return 2 * i + 2;
}
private swap(i: number, j: number) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
private compare(i: number, j: number): boolean {
// Max-heap: heap[i] should be >= heap[j]
return this.heap[i][0] >= this.heap[j][0];
}
private siftUp(i: number) {
let p = this.parent(i);
while (i > 0 && !this.compare(p, i)) {
this.swap(i, p);
i = p;
p = this.parent(i);
}
}
private siftDown(i: number) {
let maxIndex = i;
const l = this.leftChild(i);
if (l < this.size() && !this.compare(maxIndex, l)) {
maxIndex = l;
}
const r = this.rightChild(i);
if (r < this.size() && !this.compare(maxIndex, r)) {
maxIndex = r;
}
if (i !== maxIndex) {
this.swap(i, maxIndex);
this.siftDown(maxIndex);
}
}
}
function rearrangeString(s: string, k: number): string {
if (k === 0) {
return s;
}
const n = s.length;
// 1. Count character frequencies
const counts = new Map<string, number>();
for (const char of s) {
counts.set(char, (counts.get(char) || 0) + 1);
}
// 2. Build a max-heap
const pq = new PriorityQueue();
for (const [char, freq] of counts.entries()) {
pq.push([freq, char]);
}
// 3. Use a queue for cooldown
const waitQueue: FreqPair[] = [];
const result: string[] = [];
while (result.length < n) {
// If heap is empty, it's impossible
if (pq.isEmpty()) {
return "";
}
// 4. Get most frequent character
const [freq, char] = pq.pop()!;
result.push(char);
// Add to waitQueue with decremented count
waitQueue.push([freq - 1, char]);
// 5. Check if a character's cooldown is over
if (waitQueue.length === k) {
const [cooledFreq, cooledChar] = waitQueue.shift()!;
if (cooledFreq > 0) {
pq.push([cooledFreq, cooledChar]);
}
}
}
return result.join('');
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.