All problems
0121MediumHash TableStringGreedySortingHeap (Priority Queue)Counting

Paint Line Shuffle

Tracked in this browser only
Write code

Trains the technique from

LeetCode 767Reorganize String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A paint line feeds car bodies through one spray booth. Every body queued for today carries a one-letter colour code, and the whole queue reaches you as the string codes. The booth has to stop and purge its nozzle whenever two bodies in a row ask for the same colour, so the shift lead wants the queue resequenced until no two neighbouring bodies share a code. You may put the bodies in any order you like, but you must send out exactly the bodies you were given, code for code.

Several orders usually avoid every purge, so build one specific order and return it: fill the queue from front to back, and at each slot send the code with the most bodies still waiting, skipping the code you placed in the slot before; when two or more codes have the same number of bodies waiting, send the one that comes earlier in the alphabet.

If no ordering can avoid a purge, return the empty string.

Examples

Example 1

Input
codes = "bbcbca"
Output
"bcbabc"

`b` starts with three bodies waiting, so it leads; then `c` with two beats `a` with one. At the fourth slot `a` and `c` each have one body left, and `a` wins the tie.

Example 2

Input
codes = "ccdc"
Output
""

Three of the four bodies want `c`, and only one other body exists to separate them, so some pair of `c` bodies must end up adjacent.

Example 3

Input
codes = "ttssu"
Output
"ststu"

`s` and `t` both start with two bodies waiting, so the alphabet decides the first slot. The tie recurs at the third and fourth slots and is settled the same way, leaving the single `u` body last.

Constraints

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

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def paint_line_shuffle(codes: str) -> str:
Java
public String paintLineShuffle(String codes)
September 7
Apply