Reorganize String
Medium
Topics
Rearrange the characters of s so that no two adjacent characters are the same.
If no such rearrangement exists, return the empty string. If several exist, return the lexicographically smallest one, so every input has exactly one correct answer.
Example 1
a fills 2 of 3 positions, at most the 2 a string this long can hold without a clash, so the answer row exists with its copies shaded and separated.Input: s = "aab" Output: "aba" Explanation: The only arrangement that separates the two as.
Example 2
a fills 3 of 4 positions when only 2 can be kept apart, so two copies must end up adjacent whatever the arrangement and the answer is the empty string.Input: s = "aaab" Output: "" Explanation: Three as and one other character: whatever the order, two as end up adjacent.
Example 3
Input: s = "vvvlo" Output: "vlvov" Explanation: Starting with l or o leaves three vs among four remaining positions, which cannot be separated — so the answer starts with v despite v being the larger letter.
Constraints
- 1 <= s.length <= 500
- s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls
Intuition
First, when is it impossible at all? The most frequent character has to be separated by the others, so with n characters in total and m copies of the commonest one, the copies need m - 1 separators and there are only n - m characters available. That gives the condition m <= (n + 1) / 2 rounded down — example 2 fails it with three as among four characters.
Second, which arrangement? Example 3 is the instructive one. Lexicographic order wants the smallest letter first, and l is smaller than v — but committing to l leaves three vs in four slots, which the condition above rules out. So the smallest answer is not simply the greedy alphabetical choice; each candidate has to be checked against whether the remainder is still arrangeable.
That makes the shape of the solution a left-to-right construction where each position tries its candidates in alphabetical order and accepts the first one that leaves a solvable remainder. Written as a search it is obviously correct and needs no feasibility argument at all; written with the counting condition above as the test it is fast, and the condition has to account for the character just placed, which is where subtle errors live.
Approach
- Count the characters. If the commonest appears more than
(n + 1) / 2times, return the empty string. - Build the answer one position at a time, keeping the remaining counts and the character just placed.
- At each position, try the remaining characters in alphabetical order, skipping the one just placed. Take the first candidate from which the rest can still be completed.
- A search that recurses and backtracks on failure is exact; the counting condition from the intuition can replace the recursion once you trust it.
Walkthrough
s = "vvvlo" counts v:3 l:1 o:1, n = 5
impossible? m = 3 and (5 + 1) / 2 = 3, so 3 <= 3 -- possible
position 0, candidates in alphabetical order
l -> remaining v:3 o:1, four slots, commonest 3 > (4+1)/2 = 2
not completable, reject
o -> same shape, reject
v -> remaining v:2 l:1 o:1, accept
position 1, cannot repeat v
l -> remaining v:2 o:1, accept
position 2, cannot repeat l
o -> remaining v:2, two slots, both v, adjacent -- reject
v -> accept
position 3, cannot repeat v
o -> accept, position 4 takes the last v
answer vlvovComplexity
- Time — O(n * 26): each position tries at most 26 candidates, and the completability test is a scan of 26 counts. Without the test the search can backtrack, which the test prevents.
- Space — O(n): the 26 counts are O(1) and the answer is O(n). Worth separating out the part that is easy to miss:
buildrecurses once per placed character, so the call stack is itself n frames deep. It does not change the O(n) total, but on a 10^5-character input that is 10^5 stack frames, which is where a recursive solution in Python hits the default limit and an iterative loop would not.
Common Pitfalls
- Taking the alphabetically smallest available character that differs from the previous one, without checking the remainder. Example 3 is exactly this trap.
- Getting the impossibility bound wrong. It is
(n + 1) / 2rounded down, notn / 2—"aab"has two as in three characters and is fine. - Forgetting that the completability test depends on which character was just placed. Two copies left in two slots is fine in general and not fine if they are both the character just used.
- Returning any valid arrangement. Most published solutions do, and this statement asks for one specific one.
Full Solution — all languages
class Solution:
def reorganizeString(self, s):
counts = {}
for c in s:
counts[c] = counts.get(c, 0) + 1
letters = sorted(counts)
n = len(s)
out = []
dead = set()
def key(prev):
return prev + "|" + ",".join(str(counts[c]) for c in letters)
def build(prev):
if len(out) == n:
return True
k = key(prev)
if k in dead:
return False
for c in letters:
if counts[c] == 0 or c == prev:
continue
counts[c] -= 1
out.append(c)
if build(c):
return True
out.pop()
counts[c] += 1
dead.add(k)
return False
return "".join(out) if build("") else ""import java.util.*;
class Solution {
public String reorganizeString(String s) {
counts = new TreeMap<>();
for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
letters = new ArrayList<>(counts.keySet());
target = s.length();
out = new StringBuilder();
dead = new HashSet<>();
return build('\0') ? out.toString() : "";
}
private TreeMap<Character, Integer> counts;
private List<Character> letters;
private int target;
private StringBuilder out;
private Set<String> dead;
private String key(char prev) {
StringBuilder k = new StringBuilder();
k.append(prev).append('|');
for (char c : letters) k.append(counts.get(c)).append(',');
return k.toString();
}
private boolean build(char prev) {
if (out.length() == target) return true;
String k = key(prev);
if (dead.contains(k)) return false;
for (char c : letters) {
if (counts.get(c) == 0 || c == prev) continue;
counts.put(c, counts.get(c) - 1);
out.append(c);
if (build(c)) return true;
out.deleteCharAt(out.length() - 1);
counts.put(c, counts.get(c) + 1);
}
dead.add(k);
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string reorganizeString(string s) {
map<char, int> counts;
for (char c : s) counts[c]++;
vector<char> letters;
for (auto& kv : counts) letters.push_back(kv.first);
int n = (int)s.size();
string out;
set<string> dead;
function<string(char)> key = [&](char prev) {
string k(1, prev);
k += "|";
for (char c : letters) k += to_string(counts[c]) + ",";
return k;
};
function<bool(char)> build = [&](char prev) -> bool {
if ((int)out.size() == n) return true;
string k = key(prev);
if (dead.count(k)) return false;
for (char c : letters) {
if (counts[c] == 0 || c == prev) continue;
counts[c]--;
out += c;
if (build(c)) return true;
out.pop_back();
counts[c]++;
}
dead.insert(k);
return false;
};
return build('\0') ? out : "";
}
};/**
* @param {string} s
* @return {string}
*/ var reorganizeString = function(s) {
const counts = new Map();
for (const c of s) counts.set(c, (counts.get(c) || 0) + 1);
const letters = [...counts.keys()].sort();
const n = s.length, out = [], dead = new Set();
const key = (prev) => prev + "|" + letters.map(c => counts.get(c)).join(",");
const build = (prev) => {
if (out.length === n) return true;
const k = key(prev);
if (dead.has(k)) return false;
for (const c of letters) {
if (!counts.get(c) || c === prev) continue;
counts.set(c, counts.get(c) - 1);
out.push(c);
if (build(c)) return true;
out.pop();
counts.set(c, counts.get(c) + 1);
}
dead.add(k);
return false;
};
return build("") ? out.join("") : "";
};