Java String Program · S40
Reorganize String in Java
Rearrange the letters so that no letter sits next to a copy of itself. It is possible exactly when no letter takes up more than half of the string, rounded up.
Problem Statement
Rearrange the characters of a string of lowercase letters so that no two adjacent characters are equal, and return any such arrangement.
If no arrangement exists, return an empty string. Several answers can be correct; the programs below also check that their answer is valid.
Input/Output Examples
"aab"Output"aba"Explanation: the two a's are separated by b."aaabbc"Output"ababac"Explanation: a appears 3 times out of 6, exactly the allowed maximum."aaab"Output""Explanation: a appears 3 times in 4 characters, more than (4 + 1) / 2 = 2.Visual Explanation
- Countsheapa:3b:2c:1most frequent first
- Place aresultaa:2 back into the heap
- Place bresultaba is on top but was just used take the next letter
- Repeatresultababacalternate until empty
- Done"ababac"
"aaabbc" with a max-heap: always place the most frequent letter, unless it was just placed, in which case place the next most frequent one.Using the most frequent letter as early as possible keeps it from piling up at the end. If the only letter left equals the previous one, no valid arrangement exists.
Approaches
Both approaches place the most frequent letter carefully. The heap decides step by step; the even-slot method places letters by position.
Approach 1: Max-Heap Greedy (Recommended)
Idea: keep letters in a priority queue ordered by remaining count; at each step place the top letter, or the second one if the top letter was just placed.
- Count the letters and add them to a max-heap (ties broken alphabetically).
- Poll the top letter; if it equals the last placed letter, poll the next one instead.
- If no other letter is available, return
"". - Place the letter, decrease its count and push the letters back if they still have copies.
Time: O(n log k) · Space: O(k). k is the number of distinct letters, at most 26.
Approach 2: Fill Even Slots First
Idea: place the most frequent letter at indexes 0, 2, 4, …, then continue with the other letters, wrapping to the odd indexes when the even ones run out.
- Find the most frequent letter; if its count exceeds
(n + 1) / 2, return"". - Write it at even indexes first.
- Write every other letter at the next even index, then at odd indexes 1, 3, 5, …
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. For these inputs both programs print the same arrangements, but in general they can return different valid answers, so each program also prints valid=true after checking its own result.
Approach 1: Max-Heap Greedy (Recommended)
The heap always knows which letter is most at risk of being left over.
import java.util.PriorityQueue;
public class ReorganizeHeap {
// Always place the most frequent letter that differs from the previous one
static String reorganize(String s) {
int[] counts = new int[26];
for (char c : s.toCharArray()) {
counts[c - 'a']++;
}
PriorityQueue<int[]> heap = new PriorityQueue<>(
(a, b) -> a[1] != b[1] ? b[1] - a[1] : a[0] - b[0]); // count desc, then letter
for (int i = 0; i < 26; i++) {
if (counts[i] > 0) {
heap.add(new int[] {i, counts[i]});
}
}
StringBuilder result = new StringBuilder(s.length());
while (!heap.isEmpty()) {
int[] first = heap.poll();
int n = result.length();
if (n > 0 && result.charAt(n - 1) - 'a' == first[0]) {
if (heap.isEmpty()) {
return ""; // only the same letter is left
}
int[] second = heap.poll();
result.append((char) ('a' + second[0]));
if (--second[1] > 0) {
heap.add(second);
}
heap.add(first);
} else {
result.append((char) ('a' + first[0]));
if (--first[1] > 0) {
heap.add(first);
}
}
}
return result.toString();
}
static boolean noEqualNeighbours(String s) {
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] inputs = {"aab", "aaabbc", "aaab"};
for (String s : inputs) {
String r = reorganize(s);
System.out.println("\"" + s + "\" -> \"" + r + "\"" + (r.isEmpty() ? " (impossible)" : " valid=" + noEqualNeighbours(r)));
}
}
}
"aab" -> "aba" valid=true "aaabbc" -> "ababac" valid=true "aaab" -> "" (impossible)
Time complexity: O(n log k) · Space complexity: O(k).
Approach 2: Fill Even Slots First
Linear time with no heap. Because copies of a letter are written two slots apart, they can never be neighbours.
public class ReorganizeEvenSlots {
// Fill indexes 0, 2, 4, ... with the most frequent letter first, then the rest, wrapping to 1, 3, 5, ...
static String reorganize(String s) {
int n = s.length();
int[] counts = new int[26];
for (char c : s.toCharArray()) {
counts[c - 'a']++;
}
int top = 0;
for (int i = 1; i < 26; i++) {
if (counts[i] > counts[top]) {
top = i;
}
}
if (counts[top] > (n + 1) / 2) {
return ""; // the top letter cannot be kept apart
}
char[] result = new char[n];
int index = 0;
for (int round = 0; round < 27; round++) {
int letter = round == 0 ? top : round - 1;
if (round > 0 && letter == top) {
continue;
}
while (counts[letter] > 0) {
if (index >= n) {
index = 1; // even slots are full: switch to odd slots
}
result[index] = (char) ('a' + letter);
index += 2;
counts[letter]--;
}
}
return new String(result);
}
static boolean noEqualNeighbours(String s) {
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] inputs = {"aab", "aaabbc", "aaab"};
for (String s : inputs) {
String r = reorganize(s);
System.out.println("\"" + s + "\" -> \"" + r + "\"" + (r.isEmpty() ? " (impossible)" : " valid=" + noEqualNeighbours(r)));
}
}
}
"aab" -> "aba" valid=true "aaabbc" -> "ababac" valid=true "aaab" -> "" (impossible)
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Max-Heap Greedy | O(n log k) | O(k) |
| Fill Even Slots First | O(n) | O(n) |
Here n is the length of the string and k the number of distinct letters. The heap does n operations of cost log k; the even-slot method writes each character once.
Interview Tips and Recommended Approach
- Check feasibility first. A letter with count above
(n + 1) / 2makes the task impossible. - Say that several answers are valid. Test by checking the neighbours and the letter counts, not by comparing with a fixed string.
- Push letters back after placing. Forgetting to re-insert the skipped top letter loses characters.
- Know the generalisation: keeping equal letters at least
kapart uses the same heap plus a waiting queue.
Recommended Approach: Max-Heap Greedy
Why: it is a clear greedy rule backed by a standard data structure, and it extends naturally to the harder "at least k apart" version.