All problems
0222MediumHash TableStringStackGreedy

Typesetter's Rack

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2434Using a Robot to Print the Lexicographically Smallest 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 hand typesetter is composing a single line of type. Letter slugs reach the bench on a belt in a fixed order, given as the string slugs. Next to the bench stands a narrow upright rack that holds slugs one above another, and the composed line starts out empty as well.

Each step is one of exactly two moves:

  • take the slug at the head of the belt and set it on top of the rack;
  • take the slug currently on top of the rack and add it to the end of the line.

The typesetter keeps making moves until the belt and the rack are both empty, so every slug ends up somewhere in the line. Many orders of moves are possible and they compose different lines.

Return the composed line that comes first in dictionary order out of all lines the typesetter can produce.

Examples

Example 1

Input
slugs = "tqrq"
Output
"qqrt"

Set `t` and then `q` on the rack, add the top `q` to the line, set `r` and the last `q` on the rack, then add `q`, `r` and `t` to the line in that order. The line reads `qqrt`.

Example 2

Input
slugs = "dgcae"
Output
"acegd"

All five slugs travel from the belt through the rack and into the line, which ends up reading `acegd`.

Example 3

Input
slugs = "mfemf"
Output
"effmm"

Each of the five slugs is added to the line exactly once and the finished line reads `effmm`.

Constraints

  • 1 <= slugs.length <= 10^5
  • slugs consists of lowercase English letters only

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 smallest_printed_line(slugs: str) -> str:
Java
public String smallestPrintedLine(String slugs)
September 7
Apply