MediumHash TableStringGreedySortingHeap (Priority Queue)Counting

1 approach, code in every language

Problem description

Given a string s, reorder its characters so that no two adjacent characters are the same.

Return any valid rearrangement. If it is not possible to arrange the characters this way, return an empty string.

Example 1

Input: s = "aab"

Output: "aba"

Placing the two a's at positions 0 and 2 keeps them from touching.

Example 2

Input: s = "aaab"

Output: ""

Three a's cannot all be separated inside a four-character string, so no valid arrangement exists.

Constraints

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

After the pattern

Now solve one you haven't seen.

Paint Line Shuffle is our own problem on the technique behind Reorganize String: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free