#2434

Using a Robot to Print the Lexicographically Smallest String

Medium
Hash TableStringStackGreedyStackGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a greedy strategy to always choose the smallest character available to write, ensuring the result is lexicographically smallest. We utilize a stack to manage characters efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character in 's'.
  2. 2Step 2: Use a stack to hold characters from 't'.
  3. 3Step 3: Iterate through 's', adding characters to 't' and writing characters from 't' to 'p' based on their lexicographical order and remaining counts.
solution.py12 lines
1from collections import Counter
2
3def robotPrint(s):
4    count = Counter(s)
5    t = []
6    p = ''
7    for char in s:
8        t.append(char)
9        count[char] -= 1
10        while t and (not count or t[-1] <= min(count.keys())):
11            p += t.pop()
12    return p

Complexity note: This complexity is efficient as we only traverse the string a constant number of times, and the stack operations are amortized constant time.

  • 1Using a stack allows for efficient management of characters to ensure the lexicographically smallest output.
  • 2Greedy choices based on character frequency help in making optimal decisions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.