Skip to content
Problem 767 · LeetCode 767(opens in a new tab)

Reorganize String

MediumGreedy algorithms

You get a string s of lower-case letters. Rearrange its letters so that no two neighbouring characters are the same, and return the result.

Any arrangement that works is accepted. If no arrangement can keep every pair of neighbours different, return the empty string "".

Example 1

Input:  s = "aabbbc"
Output: "bababc"
Why:    the three b’s sit apart; "babcab" also works
2 more examples and the constraints

Example 2

Input:  s = "zzzy"
Output: ""
Why:    three z’s need a separator between each pair, and there is one y

Example 3

Input:  s = "q"
Output: "q"
Why:    a single letter has no neighbours

Constraints

  • 1 ≤ s.length ≤ 500
  • s holds only lower-case English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Greedy with a max-heapO(n log k)
  2. Fill even slots, then oddO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 500 lettersVerdict
Greedy with a max-heapO(n log k)
Passes; the general tool
Fill even slots, then oddO(n)
Best; two passes, no heap

n = length of s, k = number of different letters (at most 26).

Edge cases to test

  • A single letter. "q" comes back as it is.
  • Exactly at the limit. "aaaaabbbb" has 5 a’s in 9 slots: possible only as a, b, a, b, …, a.
  • One over the limit. "aaab" and "zzzy" return "".
  • All letters different. Any order works, including the input itself.

Common mistakes

  • Placing letters in alphabetical order into even slots, so the most frequent letter spills into the odd slots and lands next to itself.
  • Using n // 2 as the limit instead of (n + 1) // 2, which wrongly rejects odd lengths like "aab".
  • In the heap version, pushing the letter just used straight back, so it is picked twice in a row.

How to talk through it

  1. 1Clarify. Is any valid answer accepted? What should come back when it is impossible?
  2. 2Find the limit. A letter can take at most every other slot, so the top count must be at most (n + 1) // 2.
  3. 3Give the heap greedy. Always use the letter with the most copies left, holding back the one just used.
  4. 4Code the slot fill. Top letter into the even slots first, then everyone else, wrapping to slot 1.
  5. 5Test out loud. Run "aab", "aaab" and a single letter before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?