Algo-Sim › Heaps & Priority Queues
Reorganize String
Medium · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input
Greedy with a max-heap of letter counts: place the most common letter, and hold it back one round so it never repeats.
Problem
Rearrange the characters of string s so that no two adjacent characters are the same. Return any valid rearrangement, or the empty string "" if none exists.
Constraints
- 1 ≤ s.length ≤ 500
scontains only lowercase English letters
Edge cases to test
- Impossible: a letter count above ⌈n / 2⌉
- One character
- All letters different
Follow-up questions
- Is there a heap-free method?
- Write the most common letter into even indices, then fill the rest of the even and then odd indices: O(n).
- What if equal letters must be k apart?
- Hold popped letters in a queue for k rounds before they return to the heap (LC 358).
Solution
Java
public String reorganizeString(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) count[c - 'a']++;
// Most copies left first; equal counts go alphabetically.
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[1] != b[1] ? b[1] - a[1] : a[0] - b[0]);
for (int c = 0; c < 26; c++) {
if (count[c] > 0) heap.offer(new int[] {c, count[c]});
}
StringBuilder out = new StringBuilder();
int[] held = null;
while (!heap.isEmpty()) {
int[] top = heap.poll();
out.append((char) ('a' + top[0]));
top[1]--;
if (held != null) heap.offer(held);
held = top[1] > 0 ? top : null;
}
return held == null ? out.toString() : "";
}Python
import heapq
from collections import Counter
def reorganize_string(s):
count = Counter(s)
heap = [] # (-copies left, letter)
for c in sorted(count):
heapq.heappush(heap, (-count[c], c))
out, held = [], None
while heap:
n, c = heapq.heappop(heap)
out.append(c)
n += 1 # one copy used (n is negative)
if held:
heapq.heappush(heap, held)
held = (n, c) if n < 0 else None
return "" if held else "".join(out)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string reorganizeString(string &s) {
vector<int> count(26);
for (char c : s)
count[c - 'a']++;
// Most copies left first; equal counts go alphabetically.
auto later = [](const pair<int, int> &a, const pair<int, int> &b) { return a.second != b.second ? a.second < b.second : a.first > b.first; };
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(later)> heap(later);
for (int c = 0; c < 26; c++) {
if (count[c] > 0)
heap.push({c, count[c]});
}
string out;
optional<pair<int, int>> held;
while (!heap.empty()) {
auto top = heap.top();
heap.pop();
out += char('a' + top.first);
top.second--;
if (held)
heap.push(*held);
held = top.second > 0 ? optional<pair<int, int>>(top) : nullopt;
}
return held ? "" : out;
}
};
More Heaps & Priority Queues problems
- Kth Largest Element in an Array (Medium)
- Kth Largest Element in a Stream (Easy)
- Merge K Sorted Lists (Hard)
- Find Median from Data Stream (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Heap Sort (Build Heap + Sift Down) (Medium)
- Last Stone Weight (Easy)
- K Closest Points to Origin (Medium)
- Top K Frequent Words (Medium)
- IPO (Hard)