Lexicographically largest possible String after removal of K characters

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:  



  • Traverse the string.
  • For every character, check if it is greater than the character at the top of the stack. If found to be true, pop the top element of the stack if K > 0.
  • Insert the character into the stack.
  • After complete traversal of the string, if K > 0, then remove the top K elements of the stack.
  • Finally, store the characters in the stack as the answer. Print the answer.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement the
// above approach
class GFG{
 
static String largestString(String num, int k)
{
     
    // Final result String
    String ans = "";
 
    for(char i : num.toCharArray())
    {
         
        // If the current char exceeds the
        // character at the top of the stack
        while (ans.length() > 0 &&
               ans.charAt(ans.length() - 1) < i &&
                                          k > 0)
        {
             
            // Remove from the end of the String
            ans = ans.substring(0, ans.length() - 1);
 
            // Decrease k for the removal
            k--;
        }
 
        // Insert current character
        ans += i;
    }
 
    // Perform remaining K deletions
    // from the end of the String
    while (ans.length() > 0 && k-- > 0)
    {
        ans = ans.substring(0, ans.length() - 1);
    }
     
    // Return the String
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "zyxedcba";
    int k = 1;
 
    System.out.print(largestString(str, k) + "\n");
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement the
# above approach
def largestString(num, k):
     
    # Final result string
    ans = []
     
    for i in range(len(num)):
         
        # If the current char exceeds the
        # character at the top of the stack
        while(len(ans) and ans[-1] < num[i] and
                                 k > 0):
             
            # Remove from the end of the string
            ans.pop()
             
            # Decrease k for the removal
            k -= 1
         
        # Insert current character
        ans.append(num[i])
     
    # Perform remaining K deletions
    # from the end of the string
    while(len(ans) and k):
        k -= 1
        ans.pop()
     
    # Return the string
    return ans
     
# Driver code
str = "zyxedcba"
k = 1
 
print(*largestString(str, k), sep = "")
 
# This code is contributed by divyeshrabadiya07

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement the
// above approach
using System;
 
class GFG{
 
static String largestString(String num, int k)
{
     
    // Final result String
    String ans = "";
 
    foreach(char i in num.ToCharArray())
    {
         
        // If the current char exceeds the
        // character at the top of the stack
        while (ans.Length > 0 &&
           ans[ans.Length - 1] < i && k > 0)
        {
             
            // Remove from the end of the String
            ans = ans.Substring(0, ans.Length - 1);
 
            // Decrease k for the removal
            k--;
        }
 
        // Insert current character
        ans += i;
    }
 
    // Perform remaining K deletions
    // from the end of the String
    while (ans.Length > 0 && k-- > 0)
    {
        ans = ans.Substring(0, ans.Length - 1);
    }
     
    // Return the String
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "zyxedcba";
    int k = 1;
 
    Console.Write(largestString(str, k) + "\n");
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.