Line Notes
if (k == 0) return s;No rearrangement needed if k=0
for (char c : s) freq[c]++;Count character frequencies
auto cmp = [](pair<int, char>& a, pair<int, char>& b) { return a.first < b.first; };Comparator for max heap by frequency
priority_queue<pair<int, char>, vector<pair<int, char>>, decltype(cmp)> maxHeap(cmp);Max heap based on frequency
for (auto& p : freq) maxHeap.push({p.second, p.first});Add all characters to max heap
queue<pair<char, pair<int, int>>> cooldown;Cooldown queue to hold characters temporarily
string res;Build result string
int time = 0;Simulate time steps for scheduling
while (!maxHeap.empty() || !cooldown.empty()) {Continue until all characters placed or impossible
time++;Increment time step
if (!maxHeap.empty()) {Pick most frequent character available
auto curr = maxHeap.top(); maxHeap.pop();Pop character with highest frequency
res.push_back(curr.second);Append chosen character to result
if (curr.first > 1) {If character still has remaining count
cooldown.push({curr.second, {curr.first - 1, time + k}});Add character to cooldown with updated count and available time
} else {No character available to place
if (!cooldown.empty() && cooldown.front().second.second > time) {If cooldown not finished, no valid rearrangement
return "";Return empty string if impossible
if (!cooldown.empty() && cooldown.front().second.second == time) {Release character from cooldown when ready
auto front = cooldown.front(); cooldown.pop();Pop character from cooldown queue
maxHeap.push({front.second.first, front.first});Push character back to heap with updated count
return res.size() == s.size() ? res : "";Return valid rearrangement or empty string