Skip to content

Commit 6cbc37c

Browse files
authored
Merge pull request #1257 from nehalalifayed/patch-1
Create 402-Remove-K-Digits.cpp
2 parents 54b356b + 30a6d20 commit 6cbc37c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

cpp/402-Remove-K-Digits.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time Complexity is O(N) where N is the size of the input string.
2+
// Space complexity is O(N) as well
3+
class Solution {
4+
public:
5+
string removeKdigits(string num, int k) {
6+
int n = num.size();
7+
8+
stack<char>s;
9+
int count = k;
10+
11+
for(int i = 0 ; i < n; i++)
12+
{
13+
while(!s.empty() && count > 0 && s.top() > num[i])
14+
{
15+
s.pop();
16+
count--;
17+
}
18+
s.push(num[i]);
19+
}
20+
21+
// In case the num was already in a non increasing order (e.x: 123456)
22+
while(s.size() != n - k) s.pop();
23+
24+
string res = "";
25+
while(!s.empty())
26+
{
27+
res += s.top();
28+
s.pop();
29+
}
30+
reverse(res.begin() , res.end());
31+
// Remove the zeros from the left if they exist.
32+
while (res[0] == '0') res.erase(0 , 1);
33+
34+
35+
return (res == "") ? "0": res;
36+
}
37+
};

0 commit comments

Comments
 (0)