Reorganize String (LeetCode 767): Solution and Explanation
Given a string of lowercase letters, rearrange its characters so that no two neighbors are the same. Return any valid arrangement, or an empty string if none exists.
Watch it run step by step
Try your own input and write the code →Intuition
Trying every permutation and checking adjacency would work for tiny inputs but grows factorially. A better starting point is to ask when the task is even possible. If one letter appears more than half the time, rounded up, there are not enough other letters to separate its copies, so the answer is empty. Otherwise a valid arrangement always exists, and the question is how to build one.
The greedy idea is to always place the letter with the most copies left, because that is the letter most at risk of being stuck at the end with nothing to separate it. The only restriction is that you cannot place the same letter twice in a row. So after using a letter, set it aside for one step, place the next most frequent letter, and then put the first one back into consideration.
A max-heap keyed by remaining count gives the most frequent letter in O(log k). The reference solution keeps the just-used letter in prev instead of the heap, which enforces the cooldown of one step. If the heap is ever empty while prev is still waiting, the only letter left is the one you just placed, so no valid arrangement exists and the function returns an empty string.
Approach: Greedy max-heap with a one-step cooldown
- Count each character and build a max-heap of
[-count, char]pairs (negated because Python's heap is a min-heap). - Loop while the heap or
prevstill has characters. If the heap is empty butprevis waiting, return an empty string. - Pop the most frequent character, append it to
res, and add 1 to its negative count, using up one copy. - If
prevholds a character from the previous step, push it back into the heap and clearprev. - If the current character still has copies left, store it in
prevso it sits out the next step. - Return
reswhen everything has been placed.
Step-by-step example
s = "aab"
- Counts are a: 2, b: 1, so the heap holds [-2,'a'] and [-1,'b'].
- Pop 'a', so
res = "a"and its count becomes -1. Nothing is inprev. Since copies remain,prev = [-1,'a']. - Pop 'b', so
res = "ab"and its count becomes 0. Pushprevback into the heap and clear it. 'b' has no copies left. - Pop 'a', so
res = "aba". Its count is 0 andprevis empty. Both the heap andprevare empty, so return "aba". - For "aaab", after "aba" the heap is empty while
prev = [-1,'a']is waiting, so the function returns an empty string.
Code: Python, Java, C++
1class Solution:
2 def reorganizeString(self, s: str) -> str:
3 count = Counter(s)
4 maxHeap = [[-cnt, char] for char, cnt in count.items()]
5 heapq.heapify(maxHeap)
6
7 prev = None
8 res = ""
9 while maxHeap or prev:
10 if not maxHeap and prev:
11 return ""
12
13 cnt, char = heapq.heappop(maxHeap)
14 res += char
15 cnt += 1
16
17 if prev:
18 heapq.heappush(maxHeap, prev)
19 prev = None
20 if cnt != 0:
21 prev = [cnt, char]
22 return res1class Solution {
2 public String reorganizeString(String s) {
3 Map<Character, Integer> counts = new HashMap<>();
4 for (char c : s.toCharArray()) counts.put(c, counts.getOrDefault(c, 0) + 1);
5
6 PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> counts.get(b) - counts.get(a));
7 maxHeap.addAll(counts.keySet());
8
9 StringBuilder res = new StringBuilder();
10 while (maxHeap.size() >= 2) {
11 char a = maxHeap.poll();
12 char b = maxHeap.poll();
13
14 res.append(a);
15 res.append(b);
16
17 counts.put(a, counts.get(a) - 1);
18 counts.put(b, counts.get(b) - 1);
19
20 if (counts.get(a) > 0) maxHeap.add(a);
21 if (counts.get(b) > 0) maxHeap.add(b);
22 }
23
24 if (!maxHeap.isEmpty()) {
25 char c = maxHeap.poll();
26 if (counts.get(c) > 1) return "";
27 res.append(c);
28 }
29
30 return res.toString();
31 }
32}1class Solution {
2public:
3 string reorganizeString(string s) {
4 unordered_map<char, int> counts;
5 for (char c : s) counts[c]++;
6
7 priority_queue<pair<int, char>> maxHeap;
8 for (auto& it : counts) maxHeap.push({it.second, it.first});
9
10 string res = "";
11 while (maxHeap.size() >= 2) {
12 auto [cnt1, char1] = maxHeap.top(); maxHeap.pop();
13 auto [cnt2, char2] = maxHeap.top(); maxHeap.pop();
14
15 res += char1;
16 res += char2;
17
18 if (--cnt1 > 0) maxHeap.push({cnt1, char1});
19 if (--cnt2 > 0) maxHeap.push({cnt2, char2});
20 }
21
22 if (!maxHeap.empty()) {
23 auto [cnt, char1] = maxHeap.top();
24 if (cnt > 1) return "";
25 res += char1;
26 }
27
28 return res;
29 }
30};Time and space complexity
O(n log k)
Each of the n characters is placed with one pop and at most one push on a heap of at most k distinct letters. With k at most 26, this is effectively O(n). Building res by string concatenation can add copying cost in some languages, so a list or builder is preferable.
O(k)
The counter and heap hold at most k = 26 entries, not counting the output string.
Other approaches
Fill even indices first (time O(n), space O(n))
Check that the most frequent letter appears at most (n + 1) // 2 times. Place it at indices 0, 2, 4 and so on, then fill the remaining even and odd positions with the other letters in any order. No heap is needed.
Sort by frequency and interleave (time O(n log n), space O(n))
Sort characters by descending count, write them out into one list, then place the first half on even indices and the second half on odd indices. It is equivalent to the even-index method but uses a sort.
Common mistakes
- Pushing the current character back immediately after using it, which lets the heap return it again on the next pop and places two copies side by side.
- Forgetting the failure check when the heap is empty but
prevstill has copies, which leads to popping from an empty heap. - Mixing up the sign. The heap stores negative counts, so using a copy means adding 1, and a count of 0 means the letter is exhausted.
- Using the wrong feasibility bound. The limit is
(n + 1) // 2, so "aba" is valid even though a appears more than n / 2 times.
Frequently asked questions
When is it impossible to reorganize a string?
When some letter appears more than (n + 1) // 2 times. There are then not enough other letters to place between every pair of its copies, so two of them must end up adjacent.
Why does the greedy choice of the most frequent letter work?
The most frequent letter is the hardest to separate. Placing it whenever allowed keeps its count from outgrowing the others, which preserves the feasibility condition at every step.
What is the time complexity of reorganize string?
With a heap it is O(n log k), where k is the number of distinct letters, which is at most 26, so it behaves like O(n). The even-index method is a strict O(n).