Reorganize String

Reorganize String is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Heap (Priority Queue) Patterns pattern, in the Scheduling / Minimum Cost (Greedy with Priority Queue) subpattern.

Problem statement

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of s or return "" if not possible.

Example 1:

Input: s = "aab" Output: "aba"

Example 2:

Input: s = "aaab" Output: ""

Constraints:

- 1 <= s.length <= 500

- s consists of lowercase English letters.

Topics and companies

Topics: Hash Table, String, Greedy, Sorting, Heap (Priority Queue), Counting.

Reported in interviews at Amazon, Google, Facebook, Microsoft, Wish, Uber, Goldman Sachs.

How to practise Reorganize String on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(nloga) = O(n), a is the size of alphabet time and O(a) = O(1) space.

Open Reorganize String in the code editor, or read the Reorganize String editorial for a worked solution with its approach and complexity analysis.

Where Reorganize String sits in the DSA pattern sheet

Problems related to Reorganize String

Other problems that use the same Scheduling / Minimum Cost (Greedy with Priority Queue) and Heap (Priority Queue) Patterns techniques:

Preparing your workspace

Progress is saved as you study.