2434. Using a Robot to Print the Lexicographically Smallest String
MediumView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Longest balanced subsequence after removing characters.
Intuition
Longest balanced subsequence after removing characters. Count valid brackets using greedy: track open count, for each close try to match.
Algorithm
- 1Two passes: left-to-right count matched brackets. Or: maintain count of available opens.
Common Pitfalls
- •Remove minimum characters = keep maximum valid brackets. Greedy: track open count.
2434.cs
C#
// Approach: Stack + suffix minimum array; pop to output when stack top ≤ suffix min of remaining.
// Time: O(n) Space: O(n)
public class Solution
{
public string RobotWithString(string s)
{
int[] charCount = new int[26]; // Holds the count of each character in the string
// Increment the count for each character in the string
foreach (char ch in s)
charCount[ch - 'a']++;
StringBuilder answer = new StringBuilder(); // For building the final string
Stack<char> stack = new Stack<char>(); // To keep track of characters for processing
char minChar = 'a'; // To keep track of the smallest character that hasn't been used up
// Iterate through all characters in the string
foreach (char ch in s)
{
charCount[ch - 'a']--; // Decrease the count as we process each char
// Update the minChar to the next available smallest character
while (minChar < 'z' && charCount[minChar - 'a'] == 0)
minChar++;
stack.Push(ch); // Add current character to the stack
// Pop characters from the stack if they are smaller or equal to the current minChar
while (stack.Count > 0 && stack.Peek() <= minChar)
answer.Append(stack.Pop());
}
return answer.ToString();
}
}Was this solution helpful?
Related Problems
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 22. Generate Parentheses(Medium)
- 30. Substring with Concatenation of All Words(Hard)