Dada una string S de longitud N , la tarea es encontrar la cantidad mínima de caracteres necesarios para eliminar, de modo que cada carácter distinto en la string ocurra la misma cantidad de veces.
Ejemplos:
Entrada: S = “abcbccdddd”
Salida: 4
Explicación: Eliminar una ocurrencia de los caracteres ‘a’, ‘c’ y dos ocurrencias de ‘d’ modifica la string a “bbccdd”. Por lo tanto, cada carácter de la string aparece el mismo número de veces.Entrada: S = “geeksforgeeks”
Salida: 5
Explicación: Eliminar una ocurrencia de ‘r’, ‘f’, ‘y ‘o’ y eliminar dos ocurrencias de ‘e’ modifica S a «geeksgks».
Planteamiento: La idea es usar el multiset y el mapa . Siga los pasos a continuación para resolver el problema:
- Inicialice un map<char, int> digamos countMap y un multiset<int> digamos countMultiset para almacenar la frecuencia de cada carácter.
- Inicialice una variable, por ejemplo , ans como INT_MAX para almacenar el recuento de caracteres mínimos que se eliminarán.
- Recorra la string S e incremente el conteo de S[i] en countMap.
- Itere sobre el mapa countMap e inserte la frecuencia del carácter en countMultiset.
- Encuentre el tamaño de multiset countMultiset y guárdelo en una variable, digamos m.
- Atraviese el multiset countMultiset y actualice ans como ans = min (ans, (N- (mi)* (*it)))) e incremente i en 1 .
- Finalmente, después de completar los pasos anteriores, imprima la respuesta como ans.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find minimum number of // character removals required to make // frequency of all distinct characters the same int minimumDeletion(string s, int n) { // Stores the frequency // of each character map<char, int> countMap; // Traverse the string for (int i = 0; i < n; i++) { countMap[s[i]]++; } // Stores the frequency of each // character in sorted order multiset<int> countMultiset; // Traverse the Map for (auto it : countMap) { // Insert the frequency in multiset countMultiset.insert(it.second); } // Stores the count of elements // required to be removed int ans = INT_MAX; int i = 0; // Stores the size of multiset int m = countMultiset.size(); // Traverse the multiset for (auto j : countMultiset) { // Update the ans ans = min(ans, n - (m - i) * j); // Increment i by 1 i++; } // Return return ans; } // Driver Code int main() { // Input string S = "geeksforgeeks"; int N = S.length(); cout << minimumDeletion(S, N); return 0; }
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*; class GFG{ // Function to find minimum number of // character removals required to make // frequency of all distinct characters the same static int minimumDeletion(String s, int n) { // Stores the frequency // of each character HashMap<Character, Integer> countMap = new HashMap<>(); // Traverse the string for(int i = 0; i < n; i++) { char ch = s.charAt(i); countMap.put(ch, countMap.getOrDefault(ch, 0) + 1); } // Stores the frequency of each // character in sorted order ArrayList<Integer> countMultiset = new ArrayList<>( countMap.values()); Collections.sort(countMultiset); // Stores the count of elements // required to be removed int ans = Integer.MAX_VALUE; int i = 0; // Stores the size of multiset int m = countMultiset.size(); // Traverse the multiset for(int j : countMultiset) { // Update the ans ans = Math.min(ans, n - (m - i) * j); // Increment i by 1 i++; } // Return return ans; } // Driver Code public static void main(String[] args) { // Input String S = "geeksforgeeks"; int N = S.length(); System.out.println(minimumDeletion(S, N)); } } // This code is contributed by Kingash
Python3
# Python3 program for the above approach import sys # Function to find minimum number of # character removals required to make # frequency of all distinct characters the same def minimumDeletion(s, n): # Stores the frequency # of each character countMap = {} # Traverse the string for i in s: countMap[i] = countMap.get(i, 0) + 1 # Stores the frequency of each # character in sorted order countMultiset = [] # Traverse the Map for it in countMap: # Insert the frequency in multiset countMultiset.append(countMap[it]) # Stores the count of elements # required to be removed ans = sys.maxsize + 1 i = 0 # Stores the size of multiset m = len(countMultiset) # Traverse the multiset for j in sorted(countMultiset): # Update the ans ans = min(ans, n - (m - i) * j) # Increment i by 1 i += 1 # Return return ans # Driver Code if __name__ == '__main__': # Input S = "geeksforgeeks" N = len(S) print (minimumDeletion(S, N)) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System.Collections.Generic; using System; class GFG{ // Function to find minimum number of // character removals required to make // frequency of all distinct characters the same static int minimumDeletion(string s, int n) { // Stores the frequency // of each character Dictionary<char, int> countMap = new Dictionary<char, int>(); // Traverse the string for(int i = 0; i < n; i++) { if (countMap.ContainsKey(s[i]) == true) { countMap[s[i]] += 1; } else { countMap[s[i]] = 1; } } // Stores the frequency of each // character in sorted order List<int> countMultiset = new List<int>(); foreach(var values in countMap.Values) { countMultiset.Add(values); } countMultiset.Sort(); // Stores the count of elements // required to be removed int ans = 100000000; int index = 0; // Stores the size of multiset int m = countMultiset.Count; // Traverse the multiset foreach(var j in countMultiset) { // Update the ans ans = Math.Min(ans, n - (m - index) * j); // Increment i by 1 index++; } // Return return ans; } // Driver Code public static void Main(String[] args) { // Input string S = "geeksforgeeks"; int N = S.Length; Console.WriteLine(minimumDeletion(S, N)); } } // This code is contributed by Stream_Cipher
Javascript
<script> // JavaScript program for the above approach // Function to find minimum number of // character removals required to make // frequency of all distinct characters the same function minimumDeletion(s, n) { // Stores the frequency // of each character var countMap = new Map(); // Traverse the string for (var i = 0; i < n; i++) { if(countMap.has(s[i])) { countMap.set(s[i], countMap.get(s[i])+1); } else { countMap.set(s[i], 1); } } // Stores the frequency of each // character in sorted order var countMultiset = []; // Traverse the Map countMap.forEach((value, key) => { // Insert the frequency in multiset countMultiset.push(value); }); countMultiset.sort(); // Stores the count of elements // required to be removed var ans = 1000000000; var i = 0; // Stores the size of multiset var m = countMultiset.length; // Traverse the multiset countMultiset.forEach(j => { // Update the ans ans = Math.min(ans, n - (m - i) * j); // Increment i by 1 i++; }); // Return return ans; } // Driver Code // Input var S = "geeksforgeeks"; var N = S.length; document.write( minimumDeletion(S, N)); </script>
5
Complejidad de tiempo: O(N * log(N))
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por vermaaayush68 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA