
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements