1: First thought: brute force. Get all the permutations and check permutations one by one.
/*
Given a non-empty str and an integer k, rearrange the string such that the same
characters are at least distance k from each other.
all input strings are given in lowercase letters. If it is not possible to rearrange
the string, return an empty string "".
For example
str = "aabbcc", k = 3, return "abcabc"
str = "aaabc", k = 3, return ""
str = "aaadbbcc", k = 2, return "abacabcd", another possible "abcabcda"
*/
#include <string>
#include <iostream>
#include <unordered_map>
using namespace std;
// first thought, to get the permutation of the string and check validation.
// once we found one, we can say that there is one.
bool checkValid(string str, int k) {
unordered_map<char, int> charDistance;
for(int i = 0; i < str.size(); ++i) {
if(charDistance.find(str[i]) == charDistance.end()) {
charDistance[str[i]] = i;
} else {
if(i - charDistance[str[i]] >= k) charDistance[str[i]] = i;
else return false;
}
}
return true;
}
void rearrangeString(string str, int k, string path, string& target, bool& found) {
if(found) return;
if(str.size() == 0) {
if(checkValid(path, k)) {
found = true;
target = path;
return;
}
}
for(int i = 0; i < str.size(); ++i) {
string remaining = str.substr(0, i) + str.substr(i + 1);
rearrangeString(remaining, k, path + str[i], target, found);
}
}
string rearrangeString(string str, int k) {
string target = "";
string path = "";
bool found = false;
rearrangeString(str, k, path, target, found);
return target;
}
int main(void) {
cout << rearrangeString("aaabc", 3) << endl;
}
Second Method:
// second version, using heap and greedy.
string rearrangeString(string str, int k) {
int len = str.size();
unordered_map<char, int> charToCount;
for(int i = 0; i < str.size(); ++i) {
charToCount[str[i]]++;
}
priority_queue< pair<int, char> > maxHeap;
for(auto it = charToCount.begin(); it != charToCount.end(); ++it) {
maxHeap.push({it->second, it->first});
}
string res;
while(!maxHeap.empty()) {
vector< pair<int, char> > v;
int cnt = min(k, len); // get the minimum length.
for(int i = 0; i < cnt; ++i) {
if(maxHeap.empty()) return ""; // if left different chars numbers are smaller than the required, return false.
auto q = maxHeap.top();
maxHeap.pop();
res.push_back(q.second);
if(--q.first > 0) v.push_back(t);
len--;
}
for(auto a : v) maxHeap.push(a);
}
return res;
}