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 '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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code