Using a Robot to Print the Lexicographically Smallest String — LeetCode 2434 Python Solution
- Problem
- #2434
- Pattern
- Stack
- Reading time
- 3 min
- Source
- leetcode.com
The 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 a string s and give it to the robot.
Example
- Input
- s = "zza"
- Output
- "azz"
- Explanation
- Let p denote the written string.
Python solution
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)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + |\Sigma|) |
| Space | O(n), where n is the length of the string s and |\Sigma| is the size of the character set, which is 26 in this problem auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String?
- LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String?
- The Python solution on this page runs in O(n + |\Sigma|).
- What is the space complexity of LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String?
- The Python solution on this page uses O(n), where n is the length of the string s and |\Sigma| is the size of the character set, which is 26 in this problem auxiliary space.
- What topics does LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String cover?
- LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String is tagged Stack, Greedy, Hash Table and String on LeetCode.