
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Find the longest substring with k unique characters in a given string in Python
- Program to find length of concatenated string of unique characters in Python?
- Program to find minimum changes required for alternating binary string in Python
- Program to find minimum space plane required for skydivers in k days in python
- Program to find string after deleting k consecutive duplicate characters 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
- 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 find N-sized substrings with K distinct characters
- Python Program to find mirror characters in a string
- How to find unique characters of a string in JavaScript?
- Program to find minimum number of operations required to make one string substring of other in Python
- Program to find minimum swaps required to make given anagram in python
- Program to find minimum remove required to make valid parentheses in Python

Advertisements