- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

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

- 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 time required to complete tasks with k time gap between same type tasks in Python
- Python program to check if a string contains all unique characters
- Python program to find N-sized substrings with K distinct characters
- Program to find minimum number of bricks required to make k towers of same height in Python
- 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 remove required to make valid parentheses in Python
- Program to find minimum cost to hire k workers in Python
- Program to find minimum elements to add to form a given sum in Python

Advertisements