
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
Count Minimum Deletions to Make Character Frequencies Unique in Python
Suppose we have a string s, s is said to be good if there are no two different characters in s that have the same frequency. We have to find the minimum number of characters we need to delete to make s a good string.
So, if the input is like s = "ssstttuu", then the output will be 2 because if we delete one 't', then there will be three 's', two 't' and two 'u', then again delete one, either 't' or 'u', to make them good.
To solve this, we will follow these steps −
- val := a new map containing frequency of each character of s
- res := 0
- numlist := sort the list of all frequency values from val
- for i in range 0 to size of numlist -2, do
- if numlist[i] is non zero and numlist[i] is same as numlist[i+1], then
- numlist[i] := numlist[i] - 1
- res := res + 1
- k := i-1
- m := i
- while numlist[m] is non-zero and numlist[m] is same as numlist[k], do
- numlist[k] := numlist[k] - 1
- k := k - 1
- m := m - 1
- res := res + 1
- if numlist[i] is non zero and numlist[i] is same as numlist[i+1], then
- return res
Example
Let us see the following implementation to get better understanding −
from collections import Counter def solve(s): val = Counter(s) res = 0 numlist = sorted([i for i in val.values()]) for i in range(len(numlist)-1): if numlist[i] and numlist[i] == numlist[i+1]: numlist[i] -= 1 res += 1 k = i-1 m = i while numlist[m] and numlist[m] == numlist[k]: numlist[k] -= 1 k -= 1 m -= 1 res += 1 return res s = "ssstttuu" print(solve(s))
Input
"ssstttuu"
Output
2
Advertisements