Given a string containing lowercase English alphabets. The task is to find the minimum number of characters needed to be removed so that the remaining string contains at most 2 unique characters.
Note: The final string can have duplicate characters. The task is only to reduce the string with minimum deletions such that there can be a maximum of 2 unique characters in the resultant string.
Input: S = “geeksforgeeks”
After removing 7 characters the final string will be “geegee”
Input: S = “helloworld”
Approach: First count the occurrences of each character within the given string then just select two characters with maximum occurrence i.e. the two most frequently occurring characters in the string. And the result will be:
String length – (Occurrence of 1st most frequent character + Occurrence of 2nd most frequent character)
Below is the implementation of the above approach:
Time Complexity: O(N), where N is the length of the given String.
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.
- Minimum Cost of deletions such that string does not contains same consecutive characters
- Maximize cost of deletions to obtain string having no pair of similar adjacent characters
- Minimum number of deletions to make a string palindrome | Set 2
- Minimum number of deletions to make a string palindrome
- Minimum number of deletions so that no two consecutive are same
- Minimum deletions required such that any number X will occur exactly X times
- Deletions of "01" or "10" in binary string to make it free from "01" or "10"
- Minimize deletions in a Binary String to remove all subsequences of the form "0101"
- Reduce the string by removing K consecutive identical characters
- Reduce Hamming distance by swapping two characters
- Find the longest substring with k unique characters in a given string
- Efficiently check if a string has all unique characters without using any additional data structure
- String with maximum number of unique characters
- Minimize number of unique characters in string
- Python program to check if a string contains all unique characters
- Determine if a string has all Unique Characters
- Minimum reduce operations to convert a given string into a palindrome
- Reduce the string to minimum length with the given operation
- Minimum cost to remove the spaces between characters of a String by rearranging the characters
- Longest substring with K unique characters using Binary Search
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.