MediumHash TableStringGreedySortingHeap (Priority Queue)Counting

Reorganize String

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now