Using a Robot to Print the Lexicographically Smallest String - Problem
You control a robot that helps you create the lexicographically smallest possible string from a given input string s. The robot has an internal stack t (initially empty) and can perform exactly two operations:
- Push Operation: Take the first character from string
sand push it onto stackt - Pop Operation: Pop the top character from stack
tand write it to the result paper
Your goal is to determine the optimal sequence of operations to produce the lexicographically smallest string possible. You must continue until both s and t are completely empty.
Example: Given s = "bdda", you could push 'b' to stack, then 'd', then pop 'd' (write 'd'), pop 'b' (write 'b'), push 'd', push 'a', pop 'a' (write 'a'), pop 'd' (write 'd') to get "dbad". But there's a better sequence that gives "addb"!
Input & Output
example_1.py โ Basic Case
$
Input:
s = "bdda"
โบ
Output:
"addb"
๐ก Note:
Optimal sequence: push 'b', push 'd', push 'd', push 'a', pop 'a' (write), pop 'd' (write), pop 'd' (write), pop 'b' (write) โ "addb"
example_2.py โ Already Sorted
$
Input:
s = "abc"
โบ
Output:
"abc"
๐ก Note:
Since the string is already in lexicographical order, we can simply push each character and immediately pop it: push 'a', pop 'a', push 'b', pop 'b', push 'c', pop 'c' โ "abc"
example_3.py โ Single Character
$
Input:
s = "x"
โบ
Output:
"x"
๐ก Note:
With only one character, we must push it onto the stack and then pop it to complete the process โ "x"
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- Both s and t must be empty at the end
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Create suffix frequency map and empty stack
2
Process Characters
For each input character, make optimal push/pop decisions
3
Greedy Choice
Pop larger characters from stack only if they appear later
4
Complete
Pop remaining stack characters to finish the result
Key Takeaway
๐ฏ Key Insight: The optimal solution combines greedy decision-making with lookahead information (suffix frequencies) to ensure we always place the smallest possible character next in our result.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code