
Sponsored
Sponsored
This approach uses a stack to build the smallest possible number. We iterate over each digit in the string, and for each digit, we compare it with the top of the stack (if the stack is not empty). If the current digit is smaller than the top of the stack and we still have digits to remove, we pop from the stack. Finally, after the loop, if there are remaining digits to remove, we simply remove them from the end of the constructed stack. This ensures the smallest possible arrangement of the remaining digits.
Time Complexity: O(n), where n is the number of digits in num, because each digit is processed at most twice (once pushed and once popped).
Space Complexity: O(n), because of the space required for the stack to hold the digits.
1using System;
2using System.Text;
3
4public class Solution {
5 public string RemoveKdigits(string num, int k) {
6 var stack = new Stack<char>();
7 foreach (var digit in num) {
8 while (k > 0 && stack.Count > 0 && stack.Peek() > digit) {
9 stack.Pop();
10 k--;
11 }
12 stack.Push(digit);
13 }
14 var result = new StringBuilder();
15 foreach (var digit in stack) {
16 result.Append(digit);
17 }
18 result.Length -= k;
19 var strResult = new string(result.ToString().Reverse().ToArray());
20 return strResult.TrimStart('0') == "" ? "0" : strResult.TrimStart('0');
21 }
22}The C# solution uses a Stack<char> to push digits as they are processed. Characters satisfying the conditions are popped from the stack. The result is built by reversing the stack and removing any leading zeros that persist.