#767

Reorganize String

Medium Max-heap, place two at a time

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rearrange the letters of a string so no two adjacent letters are equal. Return any valid result, or "" if impossible.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: rearrange so no two neighbours are the same letter.

Why this works: always place the two most frequent remaining letters together; it's impossible if one letter has more than (n + 1) / 2.

Example: "aaabc"

take a, b → "ab", then a, c → "abac", then a → "abaca"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Polling one letter at a time without holding it back — you may place the same letter twice in a row.

Solve on LeetCode ↗
Complexity
  • Time: O(n log 26) = O(n).
  • Space: O(26).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon