Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Program to find minimum required chances to form a string with K unique characters in Python
Suppose we have a string s of lowercase alphabet characters, and another number k, we have to find the minimum number of required changes in the string so that the resulting string has at most k distinct characters. In this case The change is actually changing a single character to any other character.
So, if the input is like s = "wxxyyzzxx", k = 3, then the output will be 1, as we can remove the letter "w" to get 3 distinct characters (x, y, and z).
To solve this, we will follow these steps −
count := a map of each character in s and their frequency
sv := sorted list of frequency values
ans := 0
-
for i in range 0 to (size of count) - k - 1, do
ans := ans + sv[i]
return ans
Let us see the following implementation to get better understanding −
Example
from collections import Counter class Solution: def solve(self, s, k): count = Counter(s) sv = sorted(count.values()) ans = 0 for i in range(len(count) - k): ans += sv[i] return ans ob = Solution() s = "wxxyyzzxx" k = 3 print(ob.solve(s, k))
Input
"wxxyyzzxx",3
Output
1
