- Related Questions & Answers
- Find the longest substring with k unique characters in a given string in Python
- Program to find minimum space plane required for skydivers in k days in python
- Program to find minimum changes required for alternating binary string in Python
- Program to find length of concatenated string of unique characters in Python?
- Program to find string after deleting k consecutive duplicate characters in python
- Program to Find Minimum Jumps Required to Reach a Value with Different Parity in Python
- Program to find minimum number of bricks required to make k towers of same height in Python
- Python program to check if a string contains all unique characters
- Python Program to find mirror characters in a string
- Program to find minimum swaps required to make given anagram in python
- Program to find minimum cost to paint fences with k different colors in Python
- Python program to find all duplicate characters in a string
- Minimum flips required to maximize a number with k set bits in C++.
- Program to find minimum number of operations required to make one string substring of other in Python
- Program to find minimum number of hops required to reach end position in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

"wxxyyzzxx",3

1

Advertisements