Given a string S consisting of only lowercase letters, the task is to find the lexicographically largest string that can be obtained by removing K characters from the given string.
Examples:
_Input: _s = “zyxedcba”, K=1
_Output: _zyxedcb
_Explanation: _Character with smallest ASCII value from the given string is ‘a’.
Removal of ‘a’ generates the lexicographically largest possible string.
_Input: _s = “abcde”, K=2
_Output: _cde
Approach:
The idea is to use Stack Data Structure to solve the problem. Follow the steps below to solve the problem:
Below is the implementation of the above approach using inbuilt functions of the String class in C++ such as pop_back() and back() to simulate a stack:
// C++ Program to implement the
// above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
string largestString(string num,
**int**
k)
{
// final result string
string ans =
""``;
**for**
(``**auto**
i : num) {
// If the current char exceeds the
// character at the top of the stack
**while**
(ans.length() && ans.back() < i
&& k > 0) {
// Remove from the end of the string
ans.pop_back();
// Decrease k for the removal
k--;
}
// Insert current character
ans.push_back(i);
}
// Perform remaining K deletions
// from the end of the string
**while**
(ans.length() and k--) {
ans.pop_back();
}
// Return the string
**return**
ans;
}
// Driver Code
**int**
main()
{
string str =
"zyxedcba"``;
**int**
k = 1;
cout << largestString(str, k) << endl;
}
Output:
zyxedcb
Time Complexity:_ O(N)_
Auxiliary Space:_ O(N)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#greedy #stack #strings #lexicographic-ordering #code #arrays