Given a string S containing lowercase English alphabets of length N and an integer K such that K ? N. The task is to find the maximum number of non-repeating characters after removing K characters from the string.
Examples:
Input: S = “geeksforgeeks”, K = 3
Output: 6
Explanation:
Remove 1 occurrences of each g, k and s so the final string is “geeksforee” and the 6 distinct elements are g, k, s, f, o and r
Input: S = “aabbccddeeffgghh”, k = 1
Output: 1
Explanation:
Remove 1 occurrences of any character we will have only one character which will non repeating.
Naive Approach: The naive idea is to delete all possible K characters among the given string and then find the non-repeating characters in all the formed string. Print the maximum among all the count of non-repeating characters.
Time Complexity: O(N!), where N is the length of the given string.
Auxiliary Space: O(N-K)
Efficient Approach: To optimize the above approach,
The idea is to delete K characters in increasing order of frequency whose frequency is at least 2 to get the count of maximum non-repeating characters.
Below are the steps:
- Create a hash table to store the frequency of each element.
- Insert the frequency of each element in a vector V and sort the vector V in increasing order.
- For each element(say currentElement) of vector V find the minimum among K and currentElement – 1 and decrease both K and V[i] by the minimum of the two.
- Repeat the above step until K is non-zero.
- The count of 1s in vector V gives the maximum number of non-repeating characters after deleting K characters.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxDistinctChar(string s, int n, int k)
{
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++)
freq[s[i]]++;
vector< int > v;
for ( auto it = freq.begin();
it != freq.end(); it++) {
v.push_back(it->second);
}
sort(v.begin(), v.end());
for ( int i = 0; i < v.size(); i++) {
int mn = min(v[i] - 1, k);
v[i] -= mn;
k -= mn;
}
if (k > 0) {
for ( int i = 0; i < v.size(); i++) {
int mn = min(v[i], k);
v[i] -= mn;
k -= mn;
}
}
int res = 0;
for ( int i = 0; i < v.size(); i++)
if (v[i] == 1)
res++;
return res;
}
int main()
{
string S = "geeksforgeeks" ;
int N = S.size();
int K = 1;
cout << maxDistinctChar(S, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int maxDistinctChar( char []s, int n, int k)
{
HashMap<Integer,
Integer> freq = new HashMap<Integer,
Integer>();
for ( int i = 0 ; i < n; i++)
{
if (freq.containsKey(( int )s[i]))
{
freq.put(( int )s[i],
freq.get(( int )s[i]) + 1 );
}
else
{
freq.put(( int )s[i], 1 );
}
}
Vector<Integer> v = new Vector<Integer>();
for (Map.Entry<Integer, Integer> it : freq.entrySet())
{
v.add(it.getValue());
}
Collections.sort(v);
for ( int i = 0 ; i < v.size(); i++)
{
int mn = Math.min(v.get(i) - 1 , k);
v.set(i, v.get(i) - mn);
k -= mn;
}
if (k > 0 )
{
for ( int i = 0 ; i < v.size(); i++)
{
int mn = Math.min(v.get(i), k);
v.set(i, v.get(i) - mn);
k -= mn;
}
}
int res = 0 ;
for ( int i = 0 ; i < v.size(); i++)
if (v.get(i) == 1 )
res++;
return res;
}
public static void main(String[] args)
{
String S = "geeksforgeeks" ;
int N = S.length();
int K = 1 ;
System.out.print(maxDistinctChar(S.toCharArray(),
N, K));
}
}
|
Python3
from collections import defaultdict
def maxDistinctChar(s, n, k):
freq = defaultdict ( int )
for i in range (n):
freq[s[i]] + = 1
v = []
for it in freq.values():
v.append(it)
v.sort()
for i in range ( len (v)):
mn = min (v[i] - 1 , k)
v[i] - = mn
k - = mn
if (k > 0 ):
for i in range ( len (v)):
mn = min (v[i], k);
v[i] - = mn
k - = mn
res = 0
for i in range ( len (v)):
if (v[i] = = 1 ):
res + = 1
return res
if __name__ = = "__main__" :
S = "geeksforgeeks"
N = len (S)
K = 1
print (maxDistinctChar(S, N, K))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int maxDistinctChar( char []s, int n, int k)
{
Dictionary< int ,
int > freq = new Dictionary< int ,
int >();
for ( int i = 0; i < n; i++)
{
if (freq.ContainsKey(( int )s[i]))
{
freq[( int )s[i]] = freq[( int )s[i]] + 1;
}
else
{
freq.Add(( int )s[i], 1);
}
}
List< int > v = new List< int >();
foreach (KeyValuePair< int , int > it in freq)
{
v.Add(it.Value);
}
v.Sort();
for ( int i = 0; i < v.Count; i++)
{
int mn = Math.Min(v[i] - 1, k);
v[i] = v[i] - mn;
k -= mn;
}
if (k > 0)
{
for ( int i = 0; i < v.Count; i++)
{
int mn = Math.Min(v[i], k);
v[i] = v[i] - mn;
k -= mn;
}
}
int res = 0;
for ( int i = 0; i < v.Count; i++)
if (v[i] == 1)
res++;
return res;
}
public static void Main(String[] args)
{
String S = "geeksforgeeks" ;
int N = S.Length;
int K = 1;
Console.Write(maxDistinctChar(S.ToCharArray(),
N, K));
}
}
|
Javascript
<script>
function maxDistinctChar(s, n, k)
{
var freq = new Map();
for ( var i = 0; i < n; i++)
{
if (freq.has(s[i]))
freq.set(s[i], freq.get(s[i])+1)
else
freq.set(s[i], 1)
}
var v = [];
freq.forEach((value,key) => {
v.push(value);
});
v.sort()
for ( var i = 0; i < v.length; i++) {
var mn = Math.min(v[i] - 1, k);
v[i] -= mn;
k -= mn;
}
if (k > 0) {
for ( var i = 0; i < v.length; i++) {
var mn = Math.min(v[i], k);
v[i] -= mn;
k -= mn;
}
}
var res = 0;
for ( var i = 0; i < v.length; i++)
if (v[i] == 1)
res++;
return res;
}
var S = "geeksforgeeks" ;
var N = S.length;
var K = 1;
document.write( maxDistinctChar(S, N, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(26)