Applied AI Engineer (LLM) coding learning path Level 3 This level · 10 of 27

Reorganize String

Medium Heap String Counting

Problem

Rearrange the characters of a string so that no two adjacent characters are the same. Return any valid rearrangement, or an empty string if it is impossible.

Original: LeetCode 767: Reorganize String.

Examples

Example 1

Input`s = "aab"`
Output`"aba"`

Example 2

Input`s = "aaab"`
Output`""`

Three a's cannot be separated by one b.

Constraints

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 767: Reorganize Stringleetcode.com
  2. Java SE 17 API: PriorityQueuedocs.oracle.com
Previous
Next