Reorganize String (LeetCode 767): Solution and Explanation

Medium
Hash Table
String
Greedy
Counting
Heap

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Count each character and build a max-heap of [-count, char] pairs (negated because Python's heap is a min-heap).
  2. Loop while the heap or prev still has characters. If the heap is empty but prev is waiting, return an empty string.
  3. Pop the most frequent character, append it to res, and add 1 to its negative count, using up one copy.
  4. If prev holds a character from the previous step, push it back into the heap and clear prev.
  5. If the current character still has copies left, store it in prev so it sits out the next step.
  6. Return res when everything has been placed.

Step-by-step example

s = "aab"
  1. Counts are a: 2, b: 1, so the heap holds [-2,'a'] and [-1,'b'].
  2. Pop 'a', so res = "a" and its count becomes -1. Nothing is in prev. Since copies remain, prev = [-1,'a'].
  3. Pop 'b', so res = "ab" and its count becomes 0. Push prev back into the heap and clear it. 'b' has no copies left.
  4. Pop 'a', so res = "aba". Its count is 0 and prev is empty. Both the heap and prev are empty, so return "aba".
  5. 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 res

Time and space complexity

Time

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.

Space

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 prev still 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).