
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.
1#include <iostream>
2#include <string>
3#include <stack>
4using namespace std;
5
6string removeKdigits(string num, int k) {
7 stack<char> st;
8 for (char digit : num) {
9 while (k > 0 && !st.empty() && st.top() > digit) {
10 st.pop();
11 --k;
12 }
13 st.push(digit);
14 }
15 string result = "";
16 while (!st.empty()) {
17 result += st.top();
18 st.pop();
19 }
20 reverse(result.begin(), result.end());
21 result = result.substr(0, result.size() - k);
22 auto it = result.find_first_not_of('0');
23 result = it != string::npos ? result.substr(it) : "0";
24 return result;
25}The C++ solution employs a stack data structure to determine which digits to keep during processing. After processing, the stack is reversed and any additional deletions (up to k) are performed. Finally, leading zeros are stripped and the resultant string is returned.