- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if frequency of all characters can become same by one removal in Python
Suppose we have a lowercase string s. We have to check whether the frequency of all characters are same after deleting one character or not.
So, if the input is like s = "abbc", then the output will be True as we can delete one b to get string "abc" where frequency of each element is 1.
To solve this, we will follow these steps −
- occurrence := a map with all characters of s and their frequencies
- if occurrences of all characters in s are same, then
- return True
- for each char in s, do
- occurrence[char] := occurrence[char] - 1
- if occurrences of all characters in s are same, then
- return True
- occurrence[char] := occurrence[char] + 1
- return False
Example
Let us see the following implementation to get better understanding −
from collections import defaultdict def allSame(occurrence): counts = list(occurrence.values()) return all(element == counts[0] for element in counts) def solve(s): occurrence = defaultdict(int) for char in s: occurrence[char] += 1 if allSame(occurrence): return True for char in s: occurrence[char] -= 1 if allSame(occurrence): return True occurrence[char] += 1 return False s = "abbc" print(solve(s))
Input
"abbc"
Output
True
Advertisements