Using a Robot to Print the Lexicographically Smallest String - Problem

You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty:

  • Remove the first character of string s and give it to the robot. The robot will append this character to the string t.
  • Remove the last character of string t and give it to the robot. The robot will write this character on paper.

Return the lexicographically smallest string that can be written on paper.

Input & Output

Example 1 — Basic Case
$ Input: s = "zab"
Output: "abz"
💡 Note: Move z to stack, move a to stack, pop a (smaller than remaining min 'b'), move b to stack, pop b, pop z. Result: a + b + z = "abz"
Example 2 — Already Sorted
$ Input: s = "bac"
Output: "abc"
💡 Note: Move b to stack, move a to stack, pop a (≤ remaining min 'a'), move c to stack, pop c (≤ remaining min 'c'), pop b. Result: a + b + c = "abc"
Example 3 — Reverse Order
$ Input: s = "cba"
Output: "abc"
💡 Note: Move c to stack, move b to stack, pop b (≤ remaining min 'a'), move a to stack, pop a (≤ remaining min 'a'), pop c. Result: b + a + c = "bac" is wrong. Actually: we get a + b + c = "abc" by optimal popping strategy

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters

Visualization

Tap to expand
Robot String Printer - Greedy with Stack INPUT String s = "zab" z idx 0 a idx 1 b idx 2 Robot Stack t (empty) [ ] Paper (empty) " " Suffix Min: [a, a, b] ALGORITHM STEPS 1 Push 'z' to stack s="ab", t=[z] 2 Push 'a' to stack s="b", t=[z,a] 3 Pop 'a' (a <= min 'b') paper="a", t=[z] 4 Push 'b' to stack s="", t=[z,b] 5 Pop 'b' (s empty) paper="ab", t=[z] 6 Pop 'z' (stack left) paper="abz", t=[] Greedy Rule: Pop if top <= min remaining in s FINAL RESULT Lexicographically Smallest: a b z "abz" [OK] Verified Order Written: a --> b --> z Smallest chars first! Key Insight: Use a stack as the robot's buffer. Precompute suffix minimum array to know the smallest char remaining in s. Pop from stack when its top is <= suffix min (greedy: output small chars ASAP). Time: O(n), Space: O(n). TutorialsPoint - Using a Robot to Print the Lexicographically Smallest String | Greedy with Stack and Suffix Array
Asked in
Google 15 Facebook 8
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen