Taro Logo

Using a Robot to Print the Lexicographically Smallest String

#6 Most AskedMedium
0 views
Topics:
StringsStacksGreedy Algorithms

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.

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 <= 105
  • s consists of only English lowercase letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the input string `s`? Are we dealing only with lowercase English letters, or could there be uppercase letters, numbers, or special characters?
  2. What is the maximum length of the input string `s`?
  3. Can the input string `s` be empty, and if so, should the robot return an empty string?
  4. How should the robot handle duplicate characters in the input string? Do they have any special ordering or priority when deciding whether to push to the paper string or pop to the final output?
  5. Is the auxiliary paper string bounded in capacity, or can it hold up to `N` characters where `N` is the length of `s`?

Brute Force Solution

Approach

Imagine you have a jumbled sequence of letters and you want to build the alphabetically smallest possible word by moving letters between a starting pile, a temporary holding shelf, and your final output. The brute force approach involves exploring every single possible sequence of moves to see what final words they create.

Here's how the algorithm would work step-by-step:

  1. Start by looking at all the choices available at the very beginning, such as taking a letter from the starting pile or pulling the most recent letter off the holding shelf.
  2. For every choice you make, write down the path you took and then pretend to continue making choices until all the letters have been moved to your final output.
  3. Because there are multiple letters, branch out and try every combination of moving letters to the shelf and pulling them off.
  4. Once you reach the end for a particular sequence of choices, look at the final word you managed to spell out.
  5. Repeat this trial-and-error process for every other possible path and combination of moves you could have made.
  6. Compare the resulting words from all the different paths you explored.
  7. Finally, select the single word that comes first in alphabetical order from all the outcomes you generated.

Code Implementation

def robot_print_lexicographically_smallest(source_string):
    all_generated_words = []
    
    def explore_all_move_paths(source_index, holding_shelf, current_output):
        if source_index == len(source_string) and not holding_shelf:
            all_generated_words.append("".join(current_output))
            return
        
        # Explore taking a letter from the shelf first if possible to keep early letters small
        if holding_shelf:
            cloned_shelf = list(holding_shelf)
            letter_from_shelf = cloned_shelf.pop()
            current_output.append(letter_from_shelf)
            explore_all_move_paths(source_index, cloned_shelf, current_output)
            current_output.pop()
            cloned_shelf.append(letter_from_shelf)
            
        # Explore taking the next letter from the source pile and putting it onto the shelf
        if source_index < len(source_string):
            holding_shelf.append(source_string[source_index])
            explore_all_move_paths(source_index + 1, holding_shelf, current_output)
            holding_shelf.pop()
            
    explore_all_move_paths(0, [], [])
    
    # Sort all completed paths to find the ultimate lexicographically smallest resulting word
    all_generated_words.sort()
    
    return all_generated_words[0]

Big(O) Analysis

Time Complexity
O(2ⁿ) – The brute-force strategy recursively explores every possible sequence of choices between moving a letter from the starting pile of size n to the holding shelf or pulling the most recent letter off the shelf. At each of the 2n total steps involving pushes and pops, the algorithm branches into multiple recursive paths to test all combinations. This exhaustive trial-and-error search generates approximately 2ⁿ leaf nodes in the recursion tree as it evaluates every potential movement path. Therefore, the total operations approximate 2ⁿ, which simplifies to an exponential time complexity of O(2ⁿ).
Space Complexity
O(N) – The auxiliary space is primarily consumed by the holding shelf, which acts as a stack to temporarily store characters, and the output string being constructed. In the worst-case scenario, all N characters from the starting pile are pushed onto the holding shelf before being moved to the final output. Additionally, the algorithm requires precomputed suffix minimum arrays or frequency maps of size N to efficiently look up future character choices. Therefore, the total extra memory grows linearly with the input size N, resulting in an overall space complexity of O(N).

Optimal Solution

Approach

To build the alphabetically smallest possible string, we use a holding area to temporarily store letters while deciding whether to print them now or wait for better options. By looking ahead at what letters are still waiting to be processed, we can make the smartest decision at every single moment.

Here's how the algorithm would work step-by-step:

  1. Look ahead at all the remaining incoming letters to figure out what the absolute smallest letter is among them.
  2. Check the letter waiting at the very front of the holding area against the smallest remaining incoming letter.
  3. If the letter waiting in the holding area is smaller than or equal to the smallest incoming letter, print it immediately.
  4. If the incoming letters still contain something smaller than what is currently waiting in the holding area, take the next incoming letter and put it into the holding area instead of printing.
  5. Repeat this comparison process by continuously checking the holding area against the remaining incoming letters.
  6. Keep moving letters between the incoming pile, the holding area, and the final printed output until no letters are left anywhere else.
  7. By carefully balancing when to hold and when to print based on what is coming up next, the final printed result naturally forms the most alphabetically tidy string possible.

Code Implementation

def robot_print_lexicographically_smallest_string(input_string):
    from collections import Counter

    letter_frequencies = Counter(input_string)
    holding_stack = []
    output_characters = []
    minimum_available_char = 'a'

    for current_incoming_char in input_string:
        holding_stack.append(current_incoming_char)
        letter_frequencies[current_incoming_char] -= 1

        while minimum_available_char <= 'z' and letter_frequencies[minimum_available_char] == 0:
            minimum_available_char = chr(ord(minimum_available_char) + 1)

        # Pop from stack if top element is smaller or equal to the minimum remaining incoming letter.
        while holding_stack and holding_stack[-1] <= minimum_available_char:
            output_characters.append(holding_stack.pop())

    # Empty the remaining holding stack into output once all incoming letters are processed.
    while holding_stack:
        output_characters.append(holding_stack.pop())

    return "".join(output_characters)

Big(O) Analysis

Time Complexity
O(n) – To find the smallest remaining incoming letter efficiently at any moment, we precompute a suffix minimum array in O(n) time by scanning the string from right to left. Then, we iterate through the input string of size n once, pushing characters onto a stack and popping them based on our comparisons with the suffix minimums. Each of the n characters is pushed and popped from the stack at most once, meaning the total stack operations take linear time. Combining the O(n) suffix minimum pass with the O(n) processing loop results in approximately 2n total operations, which simplifies to O(n).
Space Complexity
O(N) – The auxiliary space is driven by two main data structures: a holding area stack and a precomputed suffix minimum frequency array or table. Both of these structures scale linearly with the length of the input string, denoted as N. The holding area stack can store up to N characters in the worst-case scenario where all incoming letters are deferred. Additionally, the precomputed array or frequency map requires constant space for the 26 lowercase English letters or linear space relative to N to track upcoming minimums. Therefore, the total extra memory required grows directly in proportion to N, simplifying to Big O of N space complexity.

Edge Cases

Empty string input
How to Handle:
Return an empty string immediately as no operations are needed.
String with a single character
How to Handle:
Append the character to the paper string and immediately pop it to the result string.
String with all identical characters
How to Handle:
Push all characters onto the paper string and then pop them all off in reverse or standard order.
Strictly decreasing string such as cba
How to Handle:
Keep pushing until the end, then pop everything in reverse to achieve the lexicographically smallest result abc.
Strictly increasing string such as abc
How to Handle:
Pop characters immediately as they arrive since no smaller future characters will appear.
Maximum length string scaling up to constraints
How to Handle:
Use a precomputed suffix minimum frequency array to ensure linear time complexity without exceeding time limits.
String with alternating small and large characters
How to Handle:
Greedily pop from the paper string only when the top element is smaller than or equal to the minimum remaining character in the input.
Memory constraints with deep string manipulations
How to Handle:
Use a StringBuilder in Java or list appends in Python to construct the output efficiently without excessive garbage collection.
0/8 completed