Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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:
s and give it to the robot. The robot will append this character to the string t.t and give it to the robot. The robot will write this character on paper.Return the lexicographically smallest string that can be written on the paper.
Example 1:
Input: s = "zza" Output: "azz" Explanation: Let p denote the written string. Initially p="", s="zza", t="". Perform first operation three times p="", s="", t="zza". Perform second operation three times p="azz", s="", t="".
Example 2:
Input: s = "bac" Output: "abc" Explanation: Let p denote the written string. Perform first operation twice p="", s="c", t="ba". Perform second operation twice p="ab", s="c", t="". Perform first operation p="ab", s="", t="c". Perform second operation p="abc", s="", t="".
Example 3:
Input: s = "bdda" Output: "addb" Explanation: Let p denote the written string. Initially p="", s="bdda", t="". Perform first operation four times p="", s="", t="bdda". Perform second operation four times p="addb", s="", t="".
Constraints:
1 <= s.length <= 105s consists of only English lowercase letters.Problem summary: 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 a string s and give it to the robot. The robot will append this character to the string t. Remove the last character of a string t and give it to the robot. The robot will write this character on paper. Return the lexicographically smallest string that can be written on the paper.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Stack · Greedy
"zza"
"bac"
"bdda"
find-permutation)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2434: Using a Robot to Print the Lexicographically Smallest String
class Solution {
public String robotWithString(String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
StringBuilder ans = new StringBuilder();
Deque<Character> stk = new ArrayDeque<>();
char mi = 'a';
for (char c : s.toCharArray()) {
--cnt[c - 'a'];
while (mi < 'z' && cnt[mi - 'a'] == 0) {
++mi;
}
stk.push(c);
while (!stk.isEmpty() && stk.peek() <= mi) {
ans.append(stk.pop());
}
}
return ans.toString();
}
}
// Accepted solution for LeetCode #2434: Using a Robot to Print the Lexicographically Smallest String
func robotWithString(s string) string {
cnt := make([]int, 26)
for _, c := range s {
cnt[c-'a']++
}
mi := byte('a')
stk := []byte{}
ans := []byte{}
for i := range s {
cnt[s[i]-'a']--
for mi < 'z' && cnt[mi-'a'] == 0 {
mi++
}
stk = append(stk, s[i])
for len(stk) > 0 && stk[len(stk)-1] <= mi {
ans = append(ans, stk[len(stk)-1])
stk = stk[:len(stk)-1]
}
}
return string(ans)
}
# Accepted solution for LeetCode #2434: Using a Robot to Print the Lexicographically Smallest String
class Solution:
def robotWithString(self, s: str) -> str:
cnt = Counter(s)
ans = []
stk = []
mi = 'a'
for c in s:
cnt[c] -= 1
while mi < 'z' and cnt[mi] == 0:
mi = chr(ord(mi) + 1)
stk.append(c)
while stk and stk[-1] <= mi:
ans.append(stk.pop())
return ''.join(ans)
// Accepted solution for LeetCode #2434: Using a Robot to Print the Lexicographically Smallest String
impl Solution {
pub fn robot_with_string(s: String) -> String {
let mut cnt = [0; 26];
for &c in s.as_bytes() {
cnt[(c - b'a') as usize] += 1;
}
let mut ans = Vec::with_capacity(s.len());
let mut stk = Vec::new();
let mut mi = 0;
for &c in s.as_bytes() {
cnt[(c - b'a') as usize] -= 1;
while mi < 26 && cnt[mi] == 0 {
mi += 1;
}
stk.push(c);
while let Some(&top) = stk.last() {
if (top - b'a') as usize <= mi {
ans.push(stk.pop().unwrap());
} else {
break;
}
}
}
String::from_utf8(ans).unwrap()
}
}
// Accepted solution for LeetCode #2434: Using a Robot to Print the Lexicographically Smallest String
function robotWithString(s: string): string {
const cnt = new Map<string, number>();
for (const c of s) {
cnt.set(c, (cnt.get(c) || 0) + 1);
}
const ans: string[] = [];
const stk: string[] = [];
let mi = 'a';
for (const c of s) {
cnt.set(c, (cnt.get(c) || 0) - 1);
while (mi < 'z' && (cnt.get(mi) || 0) === 0) {
mi = String.fromCharCode(mi.charCodeAt(0) + 1);
}
stk.push(c);
while (stk.length > 0 && stk[stk.length - 1] <= mi) {
ans.push(stk.pop()!);
}
}
return ans.join('');
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.