Ctrl K

Printer With a Holding Tray

Medium
A printer has a tape of letters tape and a tray where letters are stacked one on top of another. The tray starts empty. While there are letters on the tape or on the tray, you may do either of two things: - take the **first** letter off the tape and put it on top of the tray; - take the **top** letter off the tray and print it on paper (it is appended to what has been printed so far). In the end every letter ends up on paper. Return the lexicographically smallest string that can be printed this way.
Example 1
tape='dcab' → 'abcd'

Put d, c and a on the tray and print a. The top of the tray is now c, but b is still on the tape and smaller, so take b and print it, then print c and d. The result is "abcd".

Example 2
tape='cbc' → 'bcc'

Put c and b on the tray and print b. The top is c and the tape holds only another c, nothing smaller, so print c, then take and print the last c: "bcc".

Example 3
tape='ba' → 'ab'
Constraints
  • 1 ≤ tape.length ≤ 10⁵
  • tape consists of lowercase Latin letters only
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStars Eat the Smallest Letters MediumEvery Letter Once MediumErase Digits for the Smallest Number MediumSmallest Up-Down Sequence MediumBrackets With Wildcards Medium
loading Python…
Input
tape='dcab'
Expected
'abcd'

Run checks the first 3 tests in your browser. Submit checks all 64 tests on the server, hidden ones included.