Problem 468941 · medium · Level 04 Non-Linear Data Structures

No Two Same Flavours Side by Side

heaps · greedy · strings · counting

A sweet shop is laying out a row of bonbons whose flavours are the letters of s. The owner wants no two neighbouring bonbons to share a flavour. Return any arrangement of exactly these bonbons that manages it, or "" if it cannot be done.

Because many arrangements may work, your answer is checked against the rules instead of being compared to one fixed string: it must use exactly the letters of s, and no two neighbours may be equal.

Examples

Input:  s = "bbbac"
Output: "babcb"
Explanation: "bcbab" would also be accepted.

Input:  s = "ooooh"
Output: ""
Explanation: four o's cannot be kept apart by a single h.

Input:  s = "vvvlo"
Output: "vlvov"
Explanation: "vovlv" would also be accepted.

Constraints

  • 0 <= len(s) <= 10**5, lowercase letters only
  • Target complexity: O(n log a) where a is the alphabet size.

Goals

  • Detect when a rearrangement is impossible from the character counts
  • Always place the most frequent remaining character that is not the previous one
  • Hold back the just-used character for one round
Starting Python…