Leetcode 2434: Using a Robot to Print the Lexicographically Smallest String

grid47
grid47
Exploring patterns and algorithms
Mar 8, 2024 6 min read

You are given a string s and a robot that starts with an empty string t. The robot can perform two operations: one, it can remove the first character of string s and append it to t, and two, it can remove the last character of string t and write it down. The goal is to return the lexicographically smallest string that can be written on paper using these operations.
Problem
Approach
Steps
Complexity
Input: You are given a string `s` consisting of lowercase English letters.
Example: s = "hello"
Constraints:
• 1 <= s.length <= 10^5
• s consists of only lowercase English letters
Output: Return the lexicographically smallest string that can be written on paper.
Example: Output: "ehllo"
Constraints:
• The string must be lexicographically smallest.
Goal: We need to determine the lexicographically smallest string that can be obtained by performing the allowed operations on `s` and `t`.
Steps:
• 1. Traverse through the string `s` and push its characters onto the stack `t`.
• 2. After each push, check if the top character of `t` is lexicographically smaller than any remaining character in `s` and pop the character from `t` if it is.
• 3. Keep a record of the characters written down on paper to form the result string.
Goal: Consider the following constraints while designing the solution.
Steps:
• The string `s` has at least one character.
• The robot's operations must form the lexicographically smallest possible string.
Assumptions:
• The input string `s` contains only lowercase English letters.
• The solution must efficiently handle input strings up to the maximum length of 10^5.
Input: s = "hello"
Explanation: In this example, the robot will push the characters from `s` onto `t` and pop the smallest character to write down on paper. The smallest lexicographical string that can be written down is "ehllo".

Input: s = "abc"
Explanation: For the string `s = 'abc'`, the robot can directly pop all the characters from `t` to get the string "abc" written on paper.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus