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
sand give it to the robot. The robot will append this character to the stringt. - Remove the last character of string
tand 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code