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 s and push it onto stack t
  • Pop Operation: Pop the top character from stack t and 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
Robot String Construction: s="bdda" โ†’ "addb"Input Conveyor Beltbdda๐Ÿค–ROBOTStack tdโ†‘ Last In, First OutResult Paperaddb"addb"Frequency Map:b:1, d:2, a:1Decision Rule: Pop from stack if stack_top > current_charAND stack_top appears later in remaining string๐ŸŽฏ Key: Greedy choice with lookahead ensures lexicographically smallest result
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.
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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