Magicsheet logo

Using a Robot to Print the Lexicographically Smallest String

Medium
37.5%
Updated 8/1/2025

Using a Robot to Print the Lexicographically Smallest String

What is this problem about?

In the Using a Robot to Print the Lexicographically Smallest String interview question, you are given a string s and a robot with a stack. The robot can take characters from s and either put them in the stack or pop them from the stack and print them. Your goal is to find the lexicographically smallest string that the robot can print by strategically choosing when to push and when to pop.

Why is this asked in interviews?

This Lexicographically Smallest String coding problem is a challenging medium-level question asked by companies like Amazon and DE Shaw. It tests your ability to use a Stack in a Greedy way. It requires you to look ahead at the remaining characters to make the optimal decision at each step, which is a core concept in advanced algorithm design.

Algorithmic pattern used

The primary Hash Table, String, Stack, Greedy interview pattern involves maintaining a frequency count (or a suffix minimum) of the characters remaining in the input string. The greedy strategy is: as long as the character on top of the stack is smaller than or equal to any character remaining in the input string, pop it and print it. Otherwise, push the next character from the input string onto the stack. This ensures that smaller characters are printed as early as possible.

Example explanation

Input s = "bac".

  1. Freq: {b:1, a:1, c:1}. Suffix min: a, a, c.
  2. Push 'b' to stack. Remaining: {a:1, c:1}. Suffix min is 'a'.
  3. 'b' is larger than 'a', so don't pop.
  4. Push 'a' to stack. Remaining: {c:1}. Suffix min is 'c'.
  5. 'a' is smaller than 'c', so pop and print 'a'.
  6. 'b' is smaller than 'c', so pop and print 'b'.
  7. Push 'c', then pop and print 'c'. Result: "abc".

Common mistakes candidates make

The most common mistake is not looking ahead. Without knowing what characters are still to come, you might pop a character too early, blocking a smaller character from being printed later. Another error is not handling the stack correctly, leading to incorrect string construction.

Interview preparation tip

For "lexicographically smallest" problems, always think Greedy. Ask yourself: "What is the smallest character I can possibly put in the first position?" Then, use data structures like a Stack or a Priority Queue to manage the constraints on how you can access those characters.

Similar Questions