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 'c'), move c to stack, pop c, pop b. Result: a + c + b would be wrong, but we get a, then c when b > c doesn't hold, so abc
Example 3 — Reverse Order
$ Input: s = "cba"
Output: "abc"
💡 Note: Each character can wait for better ones coming later, resulting in optimal order: abc

Constraints

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

Visualization

Tap to expand
Robot String Problem: s = "zab"Input String"zab"Robot StacktOutput PaperresultMove to stackPop to paperOperations: z→stack, a→stack, pop a, b→stack, pop b, pop zFinal Result"abz"Lexicographically smallest possible!
Understanding the Visualization
1
Input
String s = 'zab', robot has empty stack t
2
Process
Use stack + suffix array to make optimal pop decisions
3
Output
Lexicographically smallest string 'abz'
Key Takeaway
🎯 Key Insight: Use a stack with lookahead - only pop characters when no better option is coming later
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