Dodomeki
Sign in

126. No Letters Side by Side

Medium

Given a string texto made of lowercase English letters, rearrange its characters so that identical letters are never next to each other.

At each position, choose a letter different from the one used at the previous position that still has occurrences available. Among the eligible letters, choose the one with the most remaining occurrences; break ties by choosing the alphabetically smallest letter.

Return the string produced by this procedure. If no valid letter is available before all characters have been used, return "".

Example 1
Input: texto = "aab"
Output: "aba"
Explanation: The letter `a` is chosen first because it has more occurrences; then `b` prevents repeating the previous letter.
Example 2
Input: texto = "aaab"
Output: ""
Explanation: It is not possible to separate all occurrences of `a`.
Example 3
Input: texto = "aabb"
Output: "abab"
Explanation: Tied letters are chosen in alphabetical order.
Constraints
  • 0 <= texto.length <= 10^5
  • `texto` contains only lowercase English letters (`a` through `z`).
HeapGreedyStrings
Caso 1
texto =
"aab"
Expected =
"aba"
Caso 2
texto =
"aaab"
Expected =
""
Caso 3
texto =
"aabb"
Expected =
"abab"

Run checks these 3 cases. Submit runs all 12, including hidden ones.