Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Remove characters from the first string which are present in the second string
Next article icon

Minimum deletions from string to reduce it to string with at most 2 unique characters

Last Updated : 21 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S     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.

Examples:  

Input: S = "geeksforgeeks" 
Output: 7 
After removing 7 characters, the final string will be "geegee"

Input: S = "helloworld" 
Output: 5 

Approach: 

First count the occurrences of each character within the given string, then just select two characters with the 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:  

C++
// C++ implementation of the above approach  #include<bits/stdc++.h> using namespace std;  // Function to find the minimum deletions int check(string s) {          int i, j;     // Array to store the occurrences      // of each characters     int fr[26] = {0} ;      // Length of the string     int n = s.size() ;     for(i = 0; i < n; i++)     {                  // ASCII of the character         char x = s[i] ;                  // Increasing the frequency for this character         fr[x-'a'] += 1 ;          }       int minimum = INT_MAX;      for(i = 0 ; i < 26; i++)     {         for( j = i + 1;j < 26; j++)         {              // Choosing two character             int z = fr[i] + fr[j] ;              // Finding the minimum deletion             minimum = min(minimum, n - z) ;         }     }      return minimum ; }  /* Driver code */ int main() {     string s ="geeksforgeeks" ;     cout << check(s) ; }  // This code is contributed by ihritik 
Java
// Java implementation of the above approach  public class GFG{  // Function to find the minimum deletions static int check(String s) {          int i,j;     // Array to store the occurrences      // of each characters     int fr[] = new int[26] ;      // Length of the string     int n = s.length() ;     for(i = 0; i < n; i++)     {                  // ASCII of the character         char x = s.charAt(i) ;                  // Increasing the frequency for this character         fr[x-'a'] += 1 ;          }       int minimum = Integer.MAX_VALUE;      for(i = 0 ; i < 26; i++)     {         for( j = i + 1;j < 26; j++)         {              // Choosing two character             int z = fr[i] + fr[j] ;              // Finding the minimum deletion             minimum = Math.min(minimum, n-z) ;         }     }      return minimum ; }      /* Driver program to test above functions */      public static void main(String []args){                      String s ="geeksforgeeks" ;         System.out.println(check(s)) ;          }     // This code is contributed by ANKITRAI1 } 
Python3
# Python3 implementation of the above approach  # Function to find the minimum deletions def check(s):      # Array to store the occurrences      # of each characters     fr =[0]*26      # Length of the string     n = len(s)     for i in range(n):          # ASCII of the character         x = ord(s[i])          # Increasing the frequency for this character         fr[x-97] += 1      minimum = 99999999999      for i in range(26):         for j in range(i + 1, 26):              # Choosing two character             z = fr[i] + fr[j]              # Finding the minimum deletion             minimum = min(minimum, n-z)      return minimum  # Driver code s ="geeksforgeeks" print(check(s)) 
C#
// C# implementation of the above approach   using System; public class GFG{   // Function to find the minimum deletions static int check(string s) {           int i,j;     // Array to store the occurrences      // of each characters     int[] fr = new int[26] ;       // Length of the string     int n = s.Length ;     for(i = 0; i < n; i++)     {                   // ASCII of the character         char x = s[i] ;                   // Increasing the frequency for this character         fr[x-'a'] += 1 ;           }         int minimum = int.MaxValue;       for(i = 0 ; i < 26; i++)     {         for( j = i + 1;j < 26; j++)         {               // Choosing two character             int z = fr[i] + fr[j] ;               // Finding the minimum deletion             minimum = Math.Min(minimum, n-z) ;         }     }       return minimum ; }       /* Driver program to test above functions */      public static void Main(){                       string s ="geeksforgeeks" ;         Console.Write(check(s)) ;           } } 
JavaScript
<script>  // Javascript implementation of the above approach  // Function to find the minimum deletions function check(s) {          var i, j;     // Array to store the occurrences      // of each characters     var fr = Array(26).fill(0);      // Length of the string     var n = s.length ;     for(i = 0; i < n; i++)     {                  // ASCII of the character         var x = s[i] ;                  // Increasing the frequency for this character         fr[x.charCodeAt(0) -'a'.charCodeAt(0)] += 1 ;          }       var minimum = 10000000000;      for(i = 0 ; i < 26; i++)     {         for( j = i + 1;j < 26; j++)         {              // Choosing two character             var z = fr[i] + fr[j] ;              // Finding the minimum deletion             minimum = Math.min(minimum, n - z) ;         }     }      return minimum ; }  /* Driver code */ var s ="geeksforgeeks" ; document.write( check(s));  </script> 

Output
7

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1) because it is using constant space.


Next Article
Remove characters from the first string which are present in the second string

I

indrajit1
Improve
Article Tags :
  • Strings
  • Python
  • DSA
  • Hash
  • frequency-counting
Practice Tags :
  • Hash
  • python
  • Strings

Similar Reads

  • Create a string with unique characters from the given N substrings
    Given an array arr[] containing N substrings consisting of lowercase English letters, the task is to return the minimum length string that contains all given parts as a substring. All characters in this new answer string should be distinct. If there are multiple strings with the following property p
    11 min read
  • Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Set 2
    Given two equal-size strings s[] and t[] of size N. In one step, choose any character of t[] and replace it with another character. Return the minimum number of steps to make t[] an anagram of s[]. Note: An Anagram of a string is a string that contains the same characters with a different (or the sa
    6 min read
  • Minimum cost to delete characters from String A to remove any subsequence as String B
    Given two strings A and B of size N and M respectively, where B is a sub-sequence of A and an array arr[] of size N, where arr[i] is the cost to delete ith character from string A. The task is to find the minimum cost to delete characters from A such that after deletion no subsequence of A is the sa
    15+ min read
  • Remove minimum characters from string to split it into three substrings under given constraints
    Given a string str of lowercase alphabets, the task is to remove minimum characters from the given string so that string can be break into 3 substrings str1, str2, and str3 such that each substring can be empty or can contains only characters 'a', 'b', and 'c' respectively.Example: Input: str = "aaa
    8 min read
  • Remove characters from the first string which are present in the second string
    Given two strings string1 and string2, remove those characters from the first string(string1) which are present in the second string(string2). Both strings are different and contain only lowercase characters.NOTE: The size of the first string is always greater than the size of the second string( |st
    15+ min read
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Find minimum number of Substrings with unique characters
    Given string 's', the task is to divide a given string s into multiple substrings, with each substring containing only unique characters. This means that no character should be repeated within a single substring. The goal is to find the minimum number of such substrings required to satisfy this cond
    12 min read
  • Split a String into two Substring such that the sum of unique characters is maximum
    Given a string str, the task is to partition the string into two substrings such that the sum of unique characters of both substrings is the maximum possible. Examples: Input: str = "abcabcd” Output: 7Explanation: Partition the given string into "abc" and "abcd", the sum of unique characters is 3 +
    14 min read
  • Minimum replacements in a string to make adjacent characters unequal
    Given a lowercase character string str of size N. In one operation any character can be changed into some other character. The task is to find the minimum number of operations such that no two adjacent characters are equal.Examples: Input: Str = "caaab" Output: 1 Explanation: Change the second a to
    6 min read
  • Minimum replacements to make adjacent characters unequal in a ternary string
    Given a string of '0', '1' and '2'. The task is to find the minimum number of replacements such that the adjacent characters are not equal. Examples: Input: s = "201220211" Output: 2 Resultant string after changes is 201210210 Input: s = "0120102" Output: 0 Approach: The following problem can be sol
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences