Rearrange Characters
A medium Heap problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Heap
- Sheets
- 2
- Core for
- 9 roles
- Platform
- LeetCode
The problem
Given a string, rearrange its characters so that no two adjacent characters are the same. Return any valid rearrangement, or an empty string if it is impossible to rearrange the characters this way.
Example 1
- Input
- s = "aab"
- Output
- "aba"
- Why
- 'a' appears twice and 'b' once. The only valid arrangement with no adjacent duplicates is "aba".
Example 2
- Input
- s = "aaab"
- Output
- ""
- Why
- 'a' appears three times and 'b' once. There is no way to arrange them without adjacent 'a's since there are too many 'a's relative to 'b'.
Example 3
- Input
- s = "aabb"
- Output
- "abab"
- Why
- 'a' and 'b' each appear twice. "abab" is a valid arrangement with no adjacent duplicates. "baba" is also valid.
Constraints
- 1 <= s.length <= 5 * 10^5
- s consists of lowercase English letters
How to think about it
Updated 2026-09-09By pigeonhole principle, if any single character appears more than (n + 1) / 2 times, no valid rearrangement exists because two identical letters must inevitably sit side by side. Otherwise, placing the most frequent remaining character alternating with another character guarantees the dominant character is exhausted without clashing.
Approaches, worst first
Max-heap greedy alternation
time O(n log 26) · space O(1)
Count frequencies into a max-heap. In each step, pop the most frequent character to place it next. To avoid immediate repetition, hold it aside while pulling the second most frequent for the subsequent spot, then re-insert both with decremented counts.
Even-odd index placementWrite this one
time O(n) · space O(1)
Sort or count characters by frequency. If the top count exceeds (n + 1) / 2, return empty. Otherwise, fill all even indices (0, 2, 4...) with the most frequent characters first, then wrap around to odd indices (1, 3, 5...) with the remaining characters.
Where people lose marks · 3
- Integer division in the impossibility condition: when n is odd, say 3, a count of 2 is legal ((3 + 1) / 2 = 2). Checking count > n / 2 would incorrectly reject valid strings like 'aab'.
- Popping only one element from the heap and pushing it back immediately. If the previous character placed was the same letter, you must hold it aside and draw a different character first.
- Assuming lowercase English letters can be indexed without checking: the alphabet size is 26, making heap operations effectively O(1), but array indices must correctly map to 'a'-'z'.
The theory behind it
Heap — the ground this problem stands on. All Heap problems
What Heap is
A heap is a specialized tree that keeps only the single most extreme item at the very top. In a min-heap, every parent node is smaller than its children, so the smallest element in the entire collection sits immediately at the root. Unlike a binary search tree, a heap does not keep all items in full sorted order. It maintains only a partial order, making it fast at giving you the single smallest or largest item without spending time sorting everything else.
When to reach for it
Reach for a heap when a problem asks for the top k largest elements, the kth smallest value, or a running median from a stream of numbers. Signals include phrases like continuously finding the cheapest item, merging k sorted linked lists, or scheduling tasks with priorities. Whenever you need repeated access to the minimum or maximum value while items are added and removed dynamically, a priority heap is the tool.
How the pattern works
To find the k largest elements, keep a min-heap of fixed size k. Push incoming numbers into the heap; whenever the heap size grows past k, pop the top item, which is the smallest among them. After processing all elements, only the k largest remain. For a running median, balance two heaps: a max-heap holding the smaller half of numbers and a min-heap holding the larger half. In code, heaps are stored compactly as flat arrays where a node at index i has children at indices 2i plus 1 and 2i plus 2.
What each operation costs
| Operation | Time |
|---|---|
| read the minimum or maximum element | O(1) |
| insert a new element and sift into position | O(log n) |
| remove the top element and sift down | O(log n) |
| build a heap from an array of n items | O(n) |
What usually goes wrong with Heap
- Using a max-heap instead of a min-heap when keeping the k largest elements, causing the largest values to be evicted while small items stay behind.
- Assuming that extracting elements by iterating over the backing array yields sorted order, without popping items from the heap one by one.
- Forgetting that standard language libraries provide a min-heap by default, leading to wrong answers when a max-heap was required.
Which roles need this problem
Heap is a core topic for these 9 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 11 more roles, including SDE / Backend Engineer, Data Engineer, ML Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Heap problems
Problem set and role mapping as of .