import heapq
from collections import Counter
class Solution:
def reorganizeString(self, s: str) -> str:
count = Counter(s)
max_heap = [(-freq, char) for char, freq in count.items()]
heapq.heapify(max_heap)
prev_freq, prev_char = 0, ''
result = []
while max_heap:
freq, char = heapq.heappop(max_heap)
result.append(char)
if prev_freq < 0:
heapq.heappush(max_heap, (prev_freq, prev_char))
freq += 1 # since freq is negative
prev_freq, prev_char = freq, char
reorganized = ''.join(result)
for i in range(1, len(reorganized)):
if reorganized[i] == reorganized[i-1]:
return ""
return reorganized
#include <queue>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
string reorganizeString(string s) {
unordered_map<char, int> count;
for (char c : s) count[c]++;
priority_queue<pair<int, char>> maxHeap;
for (auto& it : count) {
maxHeap.push({it.second, it.first});
}
string result = "";
pair<int, char> prev = {0, ' '};
while (!maxHeap.empty()) {
auto curr = maxHeap.top(); maxHeap.pop();
result += curr.second;
if (prev.first > 0) {
maxHeap.push(prev);
}
curr.first--;
prev = curr;
}
for (int i = 1; i < result.size(); ++i) {
if (result[i] == result[i-1]) return "";
}
return result;
}
};
import java.util.*;
class Solution {
public String reorganizeString(String s) {
Map<Character, Integer> count = new HashMap<>();
for (char c : s.toCharArray())
count.put(c, count.getOrDefault(c, 0) + 1);
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
for (char c : count.keySet())
maxHeap.add(new int[]{count.get(c), c});
StringBuilder result = new StringBuilder();
int[] prev = {0, ' '};
while (!maxHeap.isEmpty()) {
int[] curr = maxHeap.poll();
result.append((char)curr[1]);
if (prev[0] > 0)
maxHeap.add(prev);
curr[0]--;
prev = curr;
}
for (int i = 1; i < result.length(); i++) {
if (result.charAt(i) == result.charAt(i-1)) return "";
}
return result.toString();
}
}
function reorganizeString(s) {
const count = {};
for (const c of s) count[c] = (count[c] || 0) + 1;
const maxHeap = [];
for (const c in count) maxHeap.push([count[c], c]);
maxHeap.sort((a, b) => b[0] - a[0]);
let prev = [0, ''];
let result = '';
while (maxHeap.length > 0) {
let curr = maxHeap.shift();
result += curr[1];
if (prev[0] > 0) maxHeap.push(prev);
curr[0]--;
prev = curr;
maxHeap.sort((a, b) => b[0] - a[0]);
}
for (let i = 1; i < result.length; ++i) {
if (result[i] === result[i-1]) return '';
}
return result;
}
Given a string s
, rearrange its characters so that no two adjacent characters are the same. If it is not possible to do so, return an empty string ""
. Each character from s
must be used exactly once in the result.
s
consisting of lowercase English letters.""
if impossible.s
must be used, and each appears exactly as many times as in the original string.At first glance, the problem seems to ask for all possible rearrangements and to check which one meets the requirement that no two adjacent characters are the same. However, generating all permutations would be extremely inefficient for longer strings.
Instead, we can observe that the main challenge is to prevent high-frequency characters from being adjacent. If a character appears more than half the length of the string (rounded up), it's impossible to separate them, so we can quickly check this as a base case.
To build a valid string efficiently, we should always place the most frequent character available, but not directly after itself. We can use a max heap (priority queue) to always pick the character with the highest remaining count, and alternate between the top two characters to avoid adjacency.
s
.
Input: s = "aab"
Output: "aba"
n
.
n
is the length of the string and k
is the number of unique characters. Each heap operation is O(log k) and we do up to n operations.The key insight is to always pick the most frequent character available, while ensuring no two identical characters are adjacent. Using a max heap allows us to efficiently select and alternate characters, spacing out high-frequency letters. This greedy approach is both efficient and elegant, avoiding the pitfalls of brute-force permutation generation.