778. Reorganize String
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to rearrange a given string s so that no two adjacent characters are the same. If a valid rearrangement exists, we should return any one of them; otherwise, we return an empty string.
Solution
Reorganize String in Python
import collections
class Solution:
def reorganizeString(self, s: str) -> str:
n = len(s)
# Count character frequencies
counts = collections.Counter(s)
# Find the most frequent character and its frequency
# s.length >= 1, so counts is not empty
max_char, max_freq = counts.most_common(1)[0]
# Check if rearrangement is possible
if max_freq > (n + 1) // 2:
return ""
res = [''] * n
idx = 0
# Place the most frequent character at even indices
for _ in range(max_freq):
res[idx] = max_char
idx += 2
# Remove the most frequent character from counts to avoid placing it again
del counts[max_char]
# Place the rest of the characters
for char, freq in counts.items():
for _ in range(freq):
# If even indices are full, switch to odd indices
if idx >= n:
idx = 1
res[idx] = char
idx += 2
return "".join(res)
Reorganize String in Java
class Solution {
public String reorganizeString(String s) {
int n = s.length();
int[] counts = new int[26];
int maxFreq = 0;
int maxCharIdx = 0;
// Count character frequencies and find the most frequent one
for (char c : s.toCharArray()) {
counts[c - 'a']++;
if (counts[c - 'a'] > maxFreq) {
maxFreq = counts[c - 'a'];
maxCharIdx = c - 'a';
}
}
// Check if a valid rearrangement is possible
if (maxFreq > (n + 1) / 2) {
return "";
}
char[] res = new char[n];
int idx = 0;
// Place the most frequent character at even indices
while (counts[maxCharIdx] > 0) {
res[idx] = (char) ('a' + maxCharIdx);
idx += 2;
counts[maxCharIdx]--;
}
// Place the rest of the characters
for (int i = 0; i < 26; i++) {
while (counts[i] > 0) {
// If even indices are full, switch to odd indices
if (idx >= n) {
idx = 1;
}
res[idx] = (char) ('a' + i);
idx += 2;
counts[i]--;
}
}
return new String(res);
}
}
Reorganize String in C++
class Solution {
public:
string reorganizeString(string s) {
int n = s.length();
vector<int> counts(26, 0);
int maxFreq = 0;
int maxCharIdx = 0;
// Count character frequencies and find the most frequent one
for (char c : s) {
counts[c - 'a']++;
if (counts[c - 'a'] > maxFreq) {
maxFreq = counts[c - 'a'];
maxCharIdx = c - 'a';
}
}
// Check if a valid rearrangement is possible
if (maxFreq > (n + 1) / 2) {
return "";
}
string res(n, ' ');
int idx = 0;
// Place the most frequent character at even indices
for (int i = 0; i < maxFreq; ++i) {
res[idx] = (char)('a' + maxCharIdx);
idx += 2;
}
counts[maxCharIdx] = 0; // Mark as placed
// Place the rest of the characters
for (int i = 0; i < 26; ++i) {
while (counts[i] > 0) {
// If even indices are full, switch to odd indices
if (idx >= n) {
idx = 1;
}
res[idx] = (char)('a' + i);
idx += 2;
counts[i]--;
}
}
return res;
}
};
Reorganize String in TypeScript
function reorganizeString(s: string): string {
const n = s.length;
const counts = new Array(26).fill(0);
let maxFreq = 0;
let maxCharIdx = 0;
const aCharCode = 'a'.charCodeAt(0);
// Count character frequencies and find the most frequent one
for (let i = 0; i < n; i++) {
const charCode = s.charCodeAt(i) - aCharCode;
counts[charCode]++;
if (counts[charCode] > maxFreq) {
maxFreq = counts[charCode];
maxCharIdx = charCode;
}
}
// Check if a valid rearrangement is possible
if (maxFreq > Math.floor((n + 1) / 2)) {
return "";
}
const res = new Array(n);
let idx = 0;
// Place the most frequent character at even indices
while (counts[maxCharIdx] > 0) {
res[idx] = String.fromCharCode(aCharCode + maxCharIdx);
idx += 2;
counts[maxCharIdx]--;
}
// Place the rest of the characters
for (let i = 0; i < 26; i++) {
while (counts[i] > 0) {
// If even indices are full, switch to odd indices
if (idx >= n) {
idx = 1;
}
res[idx] = String.fromCharCode(aCharCode + i);
idx += 2;
counts[i]--;
}
}
return res.join('');
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.