πΉ Problem: 2434. Using a Robot to Print the Lexicographically Smallest String
Difficulty: #Medium
Tags: #Greedy #Stack #HashMap
π Problem Summary
Find the lexicographically smallest string that can be formed by using a robot that can do the following operations:
- Add a character to a stack
tfrom the front of a strings. - Remove the top character from the stack
tand append it to the result stringres.
---n
π§ My Thought Process
Brute Force Idea:
I was kinda close while thinking about the solution. And I actually thought of a greedy approach which is a little bit complex than the real solution. What can I say I'm still learning.-
Optimized Strategy:
The main trick is to keep track of the next smallest possible character that can be added to the stacktwhile ensuring that the characters intare in lexicographical order.- Use a stack to build the result string.
- Set the min character to 'a' initially.
- Make a frequency map of characters in
sto know how many characters are left to process. - Iterate through the string
sand for each character and add it to the stack if and update the frequency map. - Now check if the prev min character count is Zero or not, if it is zero then we set the min character to the next smallest character in the alphabet.
- Now we can check if the last character in the stack is lexicographically smaller than the current min character and if it is then we can pop the last character from the stack and append it to the result string.
Algorithm Used:
[[greedy]]
βοΈ Code Implementation (Python)
from collections import deque
from collections import Counter
class Solution:
def robotWithString(self, s: str) -> str:
s = deque(s)
c = Counter(s)
res = []
stack = []
min_char = 'a'
for ch in s:
stack.append(ch)
c[ch] -= 1
while c[min_char] == 0:
min_char = chr(ord(min_char) + 1)
while stack and stack[-1] <= min_char:
res.append(stack.pop())
return ''.join(res)
β±οΈ Time & Space Complexity
-
Time: O(n), where n is the length of the string
s. Each character is processed once. - Space: O(n), for the stack and the result string.
π§© Key Takeaways
- β
What concept or trick did I learn?
- Greedy decision-making in with stacks.
- π‘ What made this problem tricky?
- The challenge was to maintain the lexicographical order while efficiently managing the stack and the frequency of characters.
- π How will I recognize a similar problem in the future?
- Look for problems involving stacks and lexicographical order, especially those that require maintaining a sorted order while processing characters.
π Reflection (Self-Check)
- [π« ] Could I solve this without help?
- [π« ] Did I write code from scratch?
- [β ] Did I understand why it works?
- [β ] Will I be able to recall this in a week?
π Progress Tracker
| Metric | Value |
|---|---|
| Day | 11 |
| Total Problems Solved | 346 |
| Confidence Today | π |
Top comments (0)