forked from Thelalitagarwal/GFG_Daily_Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexicographically smallest string.cpp
More file actions
44 lines (44 loc) · 1.04 KB
/
Lexicographically smallest string.cpp
File metadata and controls
44 lines (44 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
int newK(int k, int n){
int t = log2(n);
if(pow(2, t) == n) return k/2;
return k*2;
}
string lexicographicallySmallest(string st, int k) {
int n = st.length();
vector<bool> vis(n, false);
stack<int> s;
string ans = "";
k = newK(k, n);
if(k >= n){
ans = "-1";
return ans;
}
if(k == 0){
return st;
}
s.push(0);
int i = 1;
while(i < n){
while(st[s.top()] > st[i]){
vis[s.top()] = true;
k--;
s.pop();
if(s.empty() or k == 0) break;
}
if(k == 0) break;
s.push(i);
i++;
}
while(k > 0 and !s.empty()){
vis[s.top()] = true;
k--;
s.pop();
}
for(int i = 0; i < n; i++){
if(!vis[i]) ans += st[i];
}
return ans;
}
};