101 Logo
onenoughtone

Problem Statement

Character Rearrangement

You're working on a text formatting tool that needs to rearrange characters in a string to improve readability.

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of s or return an empty string if not possible.

Examples

Example 1:

Input: s = "aab"
Output: "aba"
Explanation: By rearranging the characters, we get 'aba'. This is a valid arrangement since no two adjacent characters are the same.

Example 2:

Input: s = "aaab"
Output: ""
Explanation: There is no way to rearrange the characters to avoid having two adjacent 'a's.

Constraints

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

Problem Breakdown

To solve this problem, we need to:

  1. If a character appears more than (n+1)/2 times (where n is the length of the string), it's impossible to rearrange the string to avoid adjacent duplicates
  2. The greedy approach of placing the most frequent characters first works well for this problem
  3. Alternating positions (even and odd indices) can be used to distribute characters evenly
  4. A priority queue (max heap) can efficiently track character frequencies and help with the greedy placement
  5. The problem can also be solved by constructing the result string character by character, always choosing the most frequent remaining character that is different from the last one used
ProblemSolutionCode
101 Logo
onenoughtone