Reorganize String
Pattern: Top K
Always take the most frequent letter that is allowed from a max heap of counts, and keep the letter just used out of the heap for one turn. If some letter is too frequent to spread out, the answer is the empty string.
The problem
Rearrange the letters of s so that no two neighbours are equal, and return any such string, or "" if that is not
possible. "aab" can give "aba"; "aaab" gives "". The tests accept any valid answer.
Think first
- When is it impossible?
- Which letter is the most dangerous to leave for later?
- How do you stop the same letter twice in a row?
Hints
Brute force, and why it fails
Try every permutation: O(n!).
The key insight
Always place the most frequent letter that is allowed. A max heap gives it in O(log 26); holding the last-used letter out for one turn stops it repeating. The only way to get stuck is when one letter is too common.
Dry run
| out | a |
|---|---|
| held | a1 |
s = "aab": counts a 2, b 1. Pop a, append it, hold a with 1 left.
The plan
heap = max heap of (count, letter)
held = none
while heap:
(n, c) = pop; append c
if held still has count: push held
held = (n - 1, c)
return result if its length is len(s) else ""
Complexity
- Time
O(n log 26) = O(n)- Space
O(26)
Each placed letter costs a heap push and pop on at most 26 entries.
Edge cases
- One letter: itself.
- All the same letter, more than one: impossible.
- Exactly
(n + 1) / 2copies of one letter: just possible.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public String reorganizeString(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) count[c - 'a']++;
PriorityQueue<int[]> heap = new PriorityQueue<>((x, y) -> y[1] - x[1]); // {letter, count}, most left first
for (int i = 0; i < 26; i++) if (count[i] > 0) heap.add(new int[]{i, count[i]});
StringBuilder out = new StringBuilder();
int[] held = null; // the letter just used must sit out one turn
while (!heap.isEmpty()) {
int[] top = heap.poll();
out.append((char) ('a' + top[0]));
top[1]--;
if (held != null && held[1] > 0) heap.add(held);
held = top;
}
return out.length() == s.length() ? out.toString() : ""; // stuck: some letter had no partner
}
}C++
class Solution {
public:
string reorganizeString(string s) {
int count[26] = {0};
for (char c : s) count[c - 'a']++;
priority_queue<pair<int, int>> heap; // {count, letter}, most left first
for (int i = 0; i < 26; i++) if (count[i] > 0) heap.push(make_pair(count[i], i));
string out;
pair<int, int> held(0, -1); // the letter just used must sit out one turn
while (!heap.empty()) {
pair<int, int> top = heap.top();
heap.pop();
out += static_cast<char>('a' + top.second);
top.first--;
if (held.first > 0) heap.push(held);
held = top;
}
return out.size() == s.size() ? out : ""; // stuck: some letter had no partner
}
};Python
import heapq
from collections import Counter
class Solution:
def reorganizeString(self, s: str) -> str:
heap = [(-n, c) for c, n in Counter(s).items()] # most left first
heapq.heapify(heap)
out, held = [], None # the letter just used must sit out one turn
while heap:
n, c = heapq.heappop(heap)
out.append(c)
if held and held[0] < 0:
heapq.heappush(heap, held)
held = (n + 1, c)
return "".join(out) if len(out) == len(s) else "" # stuck: some letter had no partnerCommon mistakes
- Putting the letter just used straight back, so it can be picked again.
- Forgetting to check whether every letter was placed.