Using a Robot to Print the Lexicographically Smallest String
Real-world version: Typesetter's RackThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def smallest_printed_line(slugs: str) -> str:public String smallestPrintedLine(String slugs)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Lexicographically Minimum String After Removing StarsReal-world version: Clearing the Markers Off the StripMedium
- Longest PalindromeReal-world version: Longest Lintel Row of Carved TilesEasy
- Valid Parenthesis StringReal-world version: Salvage a Smudged Span TraceMedium
- Reorganize StringReal-world version: Paint Line ShuffleMedium