Leetcode 767. Reorganize String
Given a string s
, rearrange the characters of s
so that any two adjacent characters are not the same.
Return any possible rearrangement of s
or return an empty string if no such rearrangement is possible.
Input: s = "aab"
Output: "aba"
Input: s = "aaab"
Output: ""
""
.s
is 500.import java.util.PriorityQueue;
public class Solution {
public String reorganizeString(String s) {
// Character frequency array
int[] freq = new int[26];
for (char c : s.toCharArray()) {
freq[c - 'a']++;
}
// Max Heap
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[1] - a[1]);
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
if (freq[i] > (s.length() + 1) / 2) {
return ""; // Not possible to rearrange
}
maxHeap.add(new int[]{i, freq[i]});
}
}
StringBuilder result = new StringBuilder();
// Reorganize the string
while (maxHeap.size() >= 2) {
int[] first = maxHeap.poll();
int[] second = maxHeap.poll();
// Append characters to the result
result.append((char)(first[0] + 'a'));
result.append((char)(second[0] + 'a'));
// Decrease frequency and push back into heap if still remaining
if (--first[1] > 0) maxHeap.add(first);
if (--second[1] > 0) maxHeap.add(second);
}
// If one character left in heap
if (!maxHeap.isEmpty()) {
int[] last = maxHeap.poll();
if (last[1] > 1) {
return ""; // Not possible to rearrange
}
result.append((char)(last[0] + 'a'));
}
return result.toString();
}
}
Therefore, the overall time complexity is O(n), mostly dominated by the initial counting and the final string reconstruction steps.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?