Reorganize String

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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

Return any valid rearrangement of the string, or return an empty string "" if it is not possible.

Examples

Example 1:

Input: s = "aab"

Output: "aba"

Explanation: We can rearrange "aab" into "aba" so that no two adjacent characters are identical.

Example 2:

Input: s = "aaab"

Output: ""

Explanation: It is impossible to rearrange "aaab" so that no two adjacent characters are the same, because the character 'a' appears too many times.

Example 3:

Input: s = "aabb"

Output: "abab"

Explanation: Both "abab" and "baba" are valid answers.

Constraints

  • 1 <= s.length <= 500
  • s consists of lowercase English letters
Source: Top K Elements pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle