MediumNo. 2434

Using a Robot to Print the Lexicographically Smallest String — LeetCode 2434 Python Solution

Pattern
Stack
Topics
Stack, Greedy, Hash Table, String
Reading time
3 min

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

PythonSolution
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

Time
O(n + |Σ|)
Space · auxiliary
O(n), where n is the length of the string s and |Σ| is the size of the character set, which is 26 in this problem

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

Related problems
No.ProblemDifficulty
0409Longest PalindromeEasy
0736Parse Lisp ExpressionHard
0763Partition LabelsMedium
0767Reorganize StringMedium
1096Brace Expansion IIHard
1400Construct K Palindrome StringsMedium

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 + |Σ|).

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.