Leetcode: Rearrange String k Distance Apart

时间:2023-03-09 18:10:09
Leetcode: Rearrange String k Distance Apart
Given a non-empty string 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 "".

Example 1:
str = "aabbcc", k = 3 Result: "abcabc" The same letters are at least distance 3 from each other.
Example 2:
str = "aaabc", k = 3 Answer: "" It is not possible to rearrange the string.
Example 3:
str = "aaadbbcc", k = 2 Answer: "abacabcd" Another possible answer is: "abcabcda" The same letters are at least distance 2 from each other.
 Analysis:
Solution 1:
The greedy algorithm is that in each step, select the char with highest remaining count if possible (if it is not in the waiting queue).  Everytime, we add the char X with the largest remaining count, after that we should put it back to the queue (named readyQ) to find out the next largest char. HOWEVER, do not forget the constraint of K apart. So we should make char X waiting for K-1 arounds of fetching and then put it back to queue. We use another queue (named waitingQ) to store the waiting chars. Whenever, the size of this queue equals to K, the head char is ready to go back to readyQ.
Solution 2:
Based on solution 1, we do not use PriorityQueue, instead, we just use array with 26 elements to store chars' count and its next available position. Every round, we iterate through the arrays and find out the available char with max count.
NOTE: theoretically, the complexity of solution 1 using PriorityQueue is O(nlog(26)), while the complexity of solution 2 is O(n*26) which is larger than solution 1. HOWEVER, in real implementation, because solution 1 involves creating more complex data structures and sorting them, soluiont 1 is much slower than solution 2.
Solution 1: Greedy Using Heap, Time Complexity: O(Nlog(26))
What I learn: Map.Entry can be a very good Wrapper Class, you can directly use it to implement heap without writing a wrapper class yourself
 public class Solution {
public String rearrangeString(String str, int k) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
Queue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(1, new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> entry1, Map.Entry<Character, Integer> entry2) {
return entry2.getValue()-entry1.getValue();
} });
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
maxHeap.offer(entry);
}
Queue<Map.Entry<Character, Integer>> waitQueue = new LinkedList<>();
StringBuilder res = new StringBuilder(); while (!maxHeap.isEmpty()) {
Map.Entry<Character, Integer> entry = maxHeap.poll();
res.append(entry.getKey());
entry.setValue(entry.getValue()-1);
waitQueue.offer(entry);
if (waitQueue.size() >= k) {
Map.Entry<Character, Integer> unfreezeEntry = waitQueue.poll();
if (unfreezeEntry.getValue() > 0) maxHeap.offer(unfreezeEntry);
}
}
return res.length()==str.length()? res.toString() : "";
}
}

Solution2: Greedy Using Array, Time Complexity: O(N*26)

 public class Solution {
public String rearrangeString(String str, int k) {
int[] count = new int[26];
int[] nextValid = new int[26];
for (int i=0; i<str.length(); i++) {
count[str.charAt(i)-'a']++;
}
StringBuilder res = new StringBuilder();
for (int index=0; index<str.length(); index++) {
int nextCandidate = findNextValid(count, nextValid, index);
if (nextCandidate == -1) return "";
else {
res.append((char)('a' + nextCandidate));
count[nextCandidate]--;
nextValid[nextCandidate] += k;
}
}
return res.toString();
} public int findNextValid(int[] count, int[] nextValid, int index) {
int nextCandidate = -1;
int max = 0;
for (int i=0; i<count.length; i++) {
if (count[i]>max && index>=nextValid[i]) {
max = count[i];
nextCandidate = i;
}
}
return nextCandidate;
}
}