# Largest string obtained in Dictionary order after deleting K characters

Given string str of length N and an integer K, the task is to return the largest string in Dictionary Order by erasing K characters from that string.

A largest string Dictionary order is the last string when strings are arranged in alphabetical order.

Examples:

Input: str = “ritz” K = 2
Output: tz
Explanation:
There are 6 possible ways of deleting two characters from s: “ri”, “rt”, “rz”, “it”, “iz”, “tz”.
Among these strings “tz” is the largest in dictionary order.
Thus “tz” is the desired output.

Input: str = “jackie” K = 2
Output: jkie
Explanation:
The characters “a” and “c” are deleted to get the largest possible string.

Naive Approach: The idea is to find all the subsequence of the given string length N – K. Store those subsequences in a list. There will be nCm Such sequences. After the above steps print the largest string in alphabetical order stored in the list.

Time Complexity:  O(2N-K)

Efficient Approach: The idea is to use a Deque. Below are the steps:

1. Store all the characters of the string in the deque.
2. Traverse the given string and for each character in the string keep popping the characters from deque if it is less than the last character stored in the deque. Perform this operation until K is non-zero.
3. Now after the above operations, insert the current character in the deque.
4. After the above operations, the string formed by the characters stored in the deque is the resultant string.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach ` `#include ` `using` `namespace` `std;`   `// Function to find the largest ` `// string after deleting k characters ` `string largestString(``int` `n, ``int` `k, string s) ` `{ ` `    `  `    ``// Deque dq used to find the ` `    ``// largest string in dictionary ` `    ``// after deleting k characters ` `    ``deque<``char``> deq; `   `    ``// Iterate till the length ` `    ``// of the string ` `    ``for``(``int` `i = 0; i < n; ++i)` `    ``{` `        `  `        ``// Condition for popping ` `        ``// characters from deque ` `        ``while` `(deq.size() > 0 && ` `               ``deq.back() < s[i] && ` `                        ``k > 0)` `        ``{ ` `            ``deq.pop_front(); ` `            ``k--; ` `        ``} `   `        ``deq.push_back(s[i]); ` `    ``} `   `    ``// To store the resultant string ` `    ``string st = ``""``; `   `    ``// To form resultant string ` `    ``for``(``char` `c : deq) ` `        ``st = st + c; `   `    ``// Return the resultant string ` `    ``return` `st; ` `} `   `// Driver code    ` `int` `main()` `{` `    ``int` `n = 4; ` `    ``int` `k = 2; `   `    ``// Given String ` `    ``string sc = ``"ritz"``; `   `    ``// Function call ` `    ``string result = largestString(n, k, sc); `   `    ``// Print the answer ` `    ``cout << result << endl; ` `        `  `    ``return` `0;` `}`   `// This code is contributed by divyeshrabadiya07`

## Java

 `// Java program for the above approach`   `import` `java.util.ArrayDeque;` `import` `java.util.Deque;` `import` `java.util.Scanner;` `import` `java.io.IOException;`   `public` `class` `GFG {`   `    ``// Function to find the largest` `    ``// string after deleting k characters` `    ``public` `static` `String` `    ``largestString(``int` `n, ``int` `k, String sc)` `    ``{` `        ``char``[] s = sc.toCharArray();`   `        ``// Deque dq used to find the` `        ``// largest string in dictionary` `        ``// after deleting k characters` `        ``Deque deq` `            ``= ``new` `ArrayDeque<>();`   `        ``// Iterate till the length` `        ``// of the string` `        ``for` `(``int` `i = ``0``; i < n; ++i) {`   `            ``// Condition for popping` `            ``// characters from deque` `            ``while` `(deq.size() > ``0` `                   ``&& deq.getLast() < s[i]` `                   ``&& k > ``0``) {` `                ``deq.pollLast();` `                ``k--;` `            ``}`   `            ``deq.add(s[i]);` `        ``}`   `        ``// To store the resultant string` `        ``String st = ``""``;`   `        ``// To form resultant string` `        ``for` `(``char` `c : deq)` `            ``st = st + Character.toString(c);`   `        ``// Return the resultant string` `        ``return` `st;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args)` `        ``throws` `IOException` `    ``{` `        ``int` `n = ``4``;` `        ``int` `k = ``2``;`   `        ``// Given String` `        ``String sc = ``"ritz"``;`   `        ``// Function call` `        ``String result = largestString(n, k, sc);`   `        ``// Print the answer` `        ``System.out.println(result);` `    ``}` `}`

## Python3

 `# Python3 program for the above approach` `from` `collections ``import` `deque`   `# Function to find the largest` `# string after deleting k characters` `def` `largestString(n, k, sc):` `    `  `    ``s ``=` `[i ``for` `i ``in` `sc]`   `    ``# Deque dq used to find the` `    ``# largest string in dictionary` `    ``# after deleting k characters` `    ``deq ``=` `deque()`   `    ``# Iterate till the length` `    ``# of the string` `    ``for` `i ``in` `range``(n):`   `        ``# Condition for popping` `        ``# characters from deque` `        ``while` `(``len``(deq) > ``0` `and` `                ``deq[``-``1``] < s[i] ``and` `                      ``k > ``0``):` `            ``deq.popleft()` `            ``k ``-``=` `1`   `        ``deq.append(s[i])`   `    ``# To store the resultant string` `    ``st ``=` `""`   `    ``# To form resultant string` `    ``for` `c ``in` `deq:` `        ``st ``=` `st ``+` `c`   `    ``# Return the resultant string` `    ``return` `st`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `    `  `    ``n ``=` `4` `    ``k ``=` `2`   `    ``# Given String` `    ``sc ``=` `"ritz"`   `    ``# Function call` `    ``result ``=` `largestString(n, k, sc)`   `    ``# Print the answer` `    ``print``(result)`   `# This code is contributed by mohit kumar 29`

Output:

```tz

```

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 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.

Article Tags :
Practice Tags :

6

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.